-3

Consider two cases of calling a function:

void Convert(int number, int **staticPointer)
{
    int * dynamicPointer = malloc(sizeof(int));
    *dynamicPointer = number;
    *staticPointer = dynamicPointer;
}

int main()
{
    int *p;

    Convert(5, &p);

    printf("The number is: %d", *p);

    free(p);
}

The above works beautifully with no problem.

Now the case below:

void Convert(int number, int *staticPointer)
{
    int * dynamicPointer = malloc(sizeof(int));
    *dynamicPointer = number;
    staticPointer = dynamicPointer;
}

int main()
{
    int *p;

    Convert(5, p);

    printf("The number is: %d", *p);

    free(p);
}

This causes SEGFAULT. Notice that I do call the function in different ways with different parameters, and I do understand that the difference is in the calling of the function.

Can somebody please explain to me why I have to call the function as in the first example, and why the other example doesn't work (it crashes in main)?

The purpose of my program is to reference a static pointer to a specific memory address through a function.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Pavoo
  • 75
  • 2
  • 6
  • 1
    The first one changes the pointer in the `main()` function; the second changes the copy of the pointer in the `Convert()` function, but doesn't change the pointer in the `main()` function, so the pointer in `main()` is uninitialized and you are lucky that you got a crash to tell you are doing it wrong (that wasn't guaranteed). – Jonathan Leffler May 11 '16 at 14:27

2 Answers2

1

C uses pass by value for function parameter passing.

  • In the first case, by passing the address of the pointer p, you were able to change the pointer itself. So, im main(), your changes are reflected.

  • In he second case, the pointer itself cannot be changed, as it itself is passed-by-value. Once you return from the Convert() function, any changes made to p will be lost. So, in main(), you'll be accessing invalid memory (*p) which nvokes undefined behavior. Hence the crash.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

There are two things you're changing:

  • Function type
  • Function invocation

Since you want to modify the pointers value, you have to provide a pointer to the pointer to int.

See resources on pointers to pointers.

Aif
  • 11,015
  • 1
  • 30
  • 44