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]);
    }


}
Alex Kreinis
  • 147
  • 7

1 Answers1

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;
}
user2736738
  • 30,591
  • 5
  • 42
  • 56