我正在取消引用某些索引"Segmentation Fault"。如何解决?
I am getting "Segmentation Fault" dereferencing certain indices. How to fix it?
以下是导致此错误的代码:
int *marks[4];
cout<<"nPlease enter marks of PF: ";
cin>>*marks[0];
cout<<"nPlease enter marks of LA: ";
cin>>*marks[1];
cout<<"nPlease enter marks of CS: ";
cin>>*marks[2];
cout<<"nPlease enter marks of Phy: ";
cin>>*marks[3];
cout<<"nPlease enter marks of Prob: ";
cin>>*marks[4];
我在输入标记[0]和amp;标记[1]。
如果您正在声明
int *marks[4];
这并不意味着为该数组中的特定指针分配了适当的内存。
你必须分配内存,然后才能使用这样的语句进行写入
cin >> *marks[0];
如下分配内存:
for(size_t i = 0; i < 4; ++i) {
marks[i] = new int();
}
在调用CCD_ 1操作之前
不要忘记取消分配,因为它不应该再使用了:
for(size_t i = 0; i < 4; ++i) {
delete marks[i];
}
可能更好的解决方案是使用std::array<int,[size compiletime determined]>
或std::vector<int>
:
std::vector<int> marks;
根据您需要的是固定大小的阵列,还是动态分配的阵列,您可以使用
const int fixed_array_size = 30;
std::array<int,fixed_array_size> marks;
size_t array_size = 0:
std::cin >> array_size;
std::vector<int> marks(array_size);
相关文章:
- 运行同一解决方案的另一个项目的项目
- Project Euler问题4的错误解决方案
- Ardunio UNO解决了多个重叠的定时器循环
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 两个文件使用彼此的功能-如何解决
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 如何解决"invalid conversion from 'char' to 'const char*'"
- 在java中解决这段代码时面临循环中的问题
- C++:Application.cpp中抛出了未解析的外部符号(解决方案在问题的末尾,供未来的读者参考)
- 难以理解某些人解决IOI问题的源代码
- visual c++,如何获取解决方案目录中的代码
- 如何解决错误:SCIP C++中的 SCIP 阶段无效 <10>
- 节俭并发:未解决的外部问题
- IpOpt拒绝解决不受约束的问题
- 如何解决这个超硬恒星的创造问题
- 循环无限运行C++解决骑士之旅问题
- 有没有办法在远程设备上打开和编辑visual Studio 2017解决方案
- C++Matching Brackets 2解决方案不起作用
- 在 ubuntu3 上C++ goto 定义有什么解决方案吗16.04?
- 为什么这段代码不起作用,我该如何解决?