not sure where I'm screwing up here. Just learned how to dynamically allocate arrays today, and now I'm trying to have the user allocate a number of integers and have the program find the average of the inputted numbers. But right when the user is going to read in the numbers in the newly allocated array, I get a segmentation fault. Am I going out of bounds?? Or am I just treating a pointer inappropriately?? Be as harsh or honest as you want with your answers, I really just want to learn what I did wrong.
The reason for so many loops was because not only do I have to have a break in the loop for 0, but I also need to repeat the iteration whenever NULL is returned from the function or when a negative number is entered.
Thank you so much in advance!!
#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;
}