0

I'm trying to pass a pointer from main to a function I wrote, which suppose to allocate memory with the size integer and receive input from the user.

Now I know I'm doing something wrong because the pointer doesn't change back in the main function. could someone tell me what exactly I did wrong?

int rows, *newCol=NULL // the pointer inside main();//rows is the size of the array.

the function:

void buildArr(int *newCol, int rows);

void buildArr(int *newCol, int rows)
{
    int i;
    newCol = (int*)malloc(sizeof(int)*rows);
    for (i = 0; i<rows; i++)
    {
        printf("enter the value of the newCol:\n");
        printf("value #%d\n", i + 1);
        scanf("%d", &newCol[i]);
    }


}
0

1 Answer 1

3

The pointer shouldn't change in the callee. C is pass by value.

Pass the address of the pointer variable

Call it like

buildArr(&newCol,rows);
...
...
void buildArr(int **newCol, int rows)
{
    int i;
    *newCol = malloc(sizeof(int)*rows);
    ...
        scanf("%d", &(*newCol)[i]);
    }
    // nothing is returned.
}

Or return the address of the allocated chunk

newCol = buildArr(newCol, rows);
...
...
int* buildArr(int *newCol, int rows)
{
    int i;
    newCol = malloc(sizeof(int)*rows);
    ...
        scanf("%d", &newCol[i]);
    ...
    return newCol;
}
Sign up to request clarification or add additional context in comments.

12 Comments

I should send &newCol instead?
yes but I wish to do it like that, for learning purposes, what did I do wrong?
@AlexKreinis.: Wil explain.wait
@AlexKreinis.: If you again don't want to change the number of variables (resizing or shrinking..) you can simply pass the int*..that's it.
@AlexKreinis.: Like if you want to change the content of the array like setting the 0th element to 2018 then just pass the pointer. f(p) where void f(int *ptr){ ptr[0]=2018;}
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.