I assume you call that function and then try to use the a
parameter after the function returned, e.g.
a_func(a);
printf("a->n: %u", a->n);
In both cases, you pass the pointer a
by value. Changing the pointer itself in a_func()
will not be reflected outside of a_func()
. Put another way, a
inside of a_func()
is a copy of a
outside, so changes to the pointer will not reflected outside after returning.
Changing the memory a points to will be visible outside, though.
In the first case (without *
), you assign a
itself in a_func()
. As just explained, the new value of a
will be lost as soon as a_func()
returns.
In the second case (with *
), you copy the memory from [a memory location]
the memory pointed to by a
. This means, that the memory a
points to has to be valid: either it has to be on the stack, or dynamically allocated on the heap. Passing an uninitialized struct my_struct *
pointer will lead to crashes sooner or later.
Once you return, you can access the data copied via the a
pointer you passed to a_func()
.
Example for correctly using the copy version (with *
) with a local variable a
:
struct my_struct a; // Allocate a my_struct object on the stack.
a_func(&a); // Copy data from [some memory location] into a.
printf("a.n: %u", a.n); // Access and use the newly copied data in a.
Another correct version with a
allocated on the heap:
// Allocate a my_struct object on the heap and make a point to that memory.
struct my_struct *a = malloc(sizeof(my_struct));
a_func(a); // Copy data from [some memory location] into a.
printf("a->n: %u", a->n); // Access and use the newly copied data in a.
free(a); // Take care to free the allocated memory when finished!
A broken example:
struct my_struct *a; // An uninitialized pointer!
a_func(a); // The memory location a points to is overwritten - BUG!
printf("a->n: %u", a->n); // May still work but you corrupted your memory with
// the previous function call. This will lead to crashes!