【问题标题】:Segmentation Fault During Allocation of Dynamic Array C++动态数组 C++ 分配期间的分段错误
【发布时间】:2015-01-08 05:02:02
【问题描述】:

不知道我在哪里搞砸了。 今天刚刚学习了如何动态分配数组,现在我试图让用户分配一些整数并让程序找到输入数字的平均值。但是当用户要读取新分配的数组中的数字时,我遇到了分段错误。我是不是越界了??还是我只是不恰当地对待指针?用你的答案尽可能严厉或诚实,我真的只是想知道我做错了什么。

这么多循环的原因不仅是因为我必须在循环中为 0 中断,而且每当从函数返回 NULL 或输入负数时,我还需要重复迭代。

非常感谢您!

#include <iostream>
using namespace std;

int* allocateArray(int);

int main()
{
   int size;
   int *ptr = NULL;
   double sum = 0;


   cout << "Enter Number of Integers. (Enter 0 to Exit)\n";
   cin >> size;
   while (size != 0)
   {
      do
      {
         do
         {
            while (size < 0)
            {
               cout << "Enter Number of Integers. (Enter 0 to Exit) \n";
               cin >> size;
            }
            ptr = allocateArray(size);

         }
         while (ptr = NULL);

         for (int i = 0; i < size; i++)
         {
            cout << "Enter Number for Integer " << i + 1 << endl;
            cin >> ptr[i];
            //THIS is where it stops. I get a segmentation fault no matter what number 
            //Or how many numbers I enter.
            sum += *(ptr + i);
         }
         cout << "The Average is " << (sum/size) << endl;
         delete [] ptr;
         ptr = NULL;
         sum = 0;


      }
      while (size != 0);
   }


   return 0;
}


//Function meant to practice allocating a dynamic array
int* allocateArray(int size)
{
   int* tmp = NULL;

   if (size < 1)
      return NULL;
   try
   {
      tmp = new int[size];
   } catch(bad_alloc)
   {
      tmp = NULL;
   }
   if (tmp == NULL)
   {
      cout << "Failed to allocate the array!\n";
   }
   return tmp;
}

【问题讨论】:

    标签: c++ arrays dynamic segmentation-fault


    【解决方案1】:

    while (ptr = NULL); 替换为

    while (ptr == NULL);
    

    在比较和赋值运算符之间混淆是初学者的常见错误。如果您启用所有警告,您可能会收到一个警告。

    这会将NULL 分配给ptr,并将评估为false 并中断。

    【讨论】:

    • 我爱你。有效。谢谢你。没看到我就傻了。
    【解决方案2】:
     while (ptr = NULL);
    
     for (int i = 0; i < size; i++)
     {
       cout << "Enter Number for Integer " << i + 1 << endl;
       cin >> ptr[i];
       //THIS is where it stops. I get a segmentation fault no matter what number 
       //Or how many numbers I enter.
       sum += *(ptr + i);
     }
    

    您已在 while 循环中将“ptr”设置为 NULL。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-27
      • 2013-10-03
      • 1970-01-01
      • 1970-01-01
      • 2014-04-28
      相关资源
      最近更新 更多