i try to get numbers from my user and this is my function,
my function get arr as pointer and set it to a new array and return the counter of the number that i get for printing.
but when i try to print the array i get an ERROR that ther is noting
int GetNumber(int *arr)
{
int n,i=0;
int *temp;
temp = (int*)calloc(1,sizeof(int));
assert(temp);
scanf("%d",&n);
while(n != -1)
{
i++;
temp = (int*) realloc(temp,i*sizeof(int));
assert(temp);
temp[i-1] = n;
scanf("%d",&n);
}
arr = temp;
return i;
}
The problem is that you modify a local variable.
In C, all arguments are passed "by value", that means the value is copied into the scope of the function. This also happens with your pointer arr
. If you modify arr
in the function, this will never affect the caller.
The solution is to pass a pointer to what you want to modify, so your signature should look like:
int GetNumber(int **arr)
still, this pointer is passed by value, but it points to the other pointer you want to modify.
On a side note, don't cast void *
in C. It's implicitly convertible to any pointer type.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.