Access Violation (Segmentation Fault) error

Access Violation (Segmentation Fault) error

本文关键字:error Fault Segmentation Violation Access      更新时间:2023-10-16

当我运行简单的数组编码时,当我输入第7个数字时出现访问违反(分段错误)错误。如何克服这个问题?

#include <iostream>
using namespace std;
int main()
{   
  int size = 0;
  double temp[size];
  double sum = 0;
  double avg;
  cout<<"Enter how many number would you like to type: ";
  cin>>size;
  for (int i=0; i < size; ++i  ) 
  {
    cout<<endl<<"Number "<< i + 1<<": ";
    cin>>temp[i];
    sum=sum+temp[i];
  }
  avg=sum/size;
  cout <<endl<< "The sum of the array elements is: " << sum << endl;
  cout << "The average of the array elements is: " << avg << endl<<endl;
  system("pause");
   return 0; 
}

正如其他注释解释的那样,在您的情况下,tmp[]的大小为0,因为它是用非const表达式size初始化的。当你访问数组边界之外的内存时,就会出现段错误(c++不验证数组边界)。

为什么你需要数组呢?你可以重新分配变量…

int main()
{   
  int size = 0;
  double temp;
  double sum = 0;
  double avg;
  cout<<"Enter how many number would you like to type: ";
  cin>>size;
  for (int i=0; i < size; ++i  ) 
  {
    cout<<endl<<"Number "<< i + 1<<": ";
    cin>>temp;
    sum=sum+temp;
  }

或者你应该使用vector<double> tmp

int main() {
    int size = 0;
    double temp[size];

在c++中是有效的。如果您的编译器编译它,则无法根据c++语言标准预测结果程序的外观或行为。数组(严格地说:完整的数组类型)必须有一个由常量表达式给出的严格正边界。

当您分配这样一个数组时,它的大小是固定的,并且必须在编译时知道。一般来说,不能使用变量来表示大小,但是在本例中,由于size是在前面用常量表达式初始化的,因此它的值在编译时是已知的。编译器有效地将double temp[size]替换为double temp[0](也许这里有一个警告会很好)。显然,当您尝试访问一个(固定)大小为0的数组的元素时,它的行为不会很好。

您正在尝试动态分配数组大小,您的方法是不正确的,当您试图从内存访问无效地址时,会发生分段故障,这意味着数组的位置不存在。我希望这能解决你的问题:

#include <iostream>
using namespace std;
int main()
{
  int size;
  int sum = 0;
  float avg;
  std::cout << "Number of elements you want to input: ";
  std::cin >> size;
  int *array = new int[size]; //assign array size dynamically
  for (int i = 0; i < size; i++) //find sum
  {
      std::cout << "Input val " << i << ": ";
      std::cin >> array[i];
      sum = sum + array[i];
  }
  avg = sum / size; //cal avg
  cout <<endl<< "Sum: " << sum << endl; //display
  cout << "Avg: " << avg << endl;
  delete [] array; //free memory
  return 0;
}
相关文章: