我正在取消引用某些索引"Segmentation Fault"。如何解决?

I am getting "Segmentation Fault" dereferencing certain indices. How to fix it?

本文关键字:何解决 解决 Fault Segmentation 取消 引用 索引      更新时间:2023-10-16

以下是导致此错误的代码:

  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);