【发布时间】: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