0

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;
}
2
  • 1
    You are only modifying the address of the pointer on the current stack frame, not on the calling one. You should use int **arr as an argument and realloc using *arr = realloc(*arr, ...), and thus pass a pointer to an int pointer like so: GetNumber(&the_arr) Commented May 27, 2017 at 21:21
  • Do not realloc and assign the return to your original variable. If realloc fails, the original temp is NOT freed and NULL is returned and assigned to temp causing you to lose the reference to the block of memory pointed to by temp creating a memory leak. Instead use a temporary pointer, e.g. void *t = realloc (temp, i * sizeof *temp); if (t) temp = t; Commented May 27, 2017 at 21:55

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Here is a handy link for the malloc cast (you will find you need it over-and-over again), Do I cast the result of malloc?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.