I have to build a program using nothing but pointers to calculate the average of a random set of numbers inputted by the user. The pointers must be passed by reference as parameters for the getAverage() function and the function must return the reference of a value. I'm pretty new to pointers and don't fully understand their use, but this is my code that won't compile.
//
#include <iostream>
usingnamespace std;
int * getAverage(int * tot, int * numbers);
int main(void)
{
int * b = newint();
int * i = newint(0);
int * sum= newint(0);
cout<<"Enter a series of positive numbers\nEntering a negative number will stop input."<<endl;
do{
cin>>*b;
if(*b>0){
*sum=*sum+*b;
*i++;
}
} while(*b>0);
getAverage(*sum, *i);
return 0;
}
int * getAverage(int * tot, int * numbers){
int * average = newint( *tot/(*numbers));
return *average;
}
The pointer *i and the getAverage() function are the issues here. Any help would be appreciated.
getAverage(*sum, *i); This is passing in the dereferenced values of these pointers. Basically you're passing ints when it's expecting pointers to ints. Drop the dereference operator there.
Also, you have a lot of dynamically assigned memory here with no deletes. Shouldn't cause any errors, but it's bad practice to get into. Rule of thumb, there should be a delete for every new you use.
Now you're returning the pointer, which is what you want I believe. If you want to output the value of the pointer, you'll need to dereference it in the calling function.
Delete is used whenever you dynamically assign memory. When you make a variable using new, you are dynamically assigning memory to that. What this does is tells the program to set aside memory for this size of variable, no matter what. This means that that block of memory is occupied even after you lose scope of the variable and can't access it anymore. This is known as a memory leak. As you can see, if this happens a lot, you will run out of memory and your program will crash.
So basically, whenever your done with a variable that you assigned using new, you need to call delete on it.
You also need to be careful about pointers pointing to dynamically assigned memory locations. If you delete one of these variables, you also need to make sure to not dereference that pointer without first setting it to null, or to another object. If you don't do this, this is known as a dangling pointer.
So as you can probably see, dynamic memory can be pretty complicated.
It turns out I just needed to surround the i pointer being incremented in parentheses. Thank you for your help though.
If you get a minute, would you mind showing me what a delete statement looks like and how to use one?
int* arr;
arr = newint[10]; //Dynamically created array.
//Doing some array stuffs here....
//And now I'm done with it, I need to get rid of it.
delete [] arr;
Note, when deleting a single element, ie not a container, you just use delete without the brackets. If you are deleting an array, you use the brackets.