C Assign Pointer to NULL
c, function, pointers
Solution
It's because the pointer is passed by value and not by reference. If you want to change the pointer inside the function you need to pass the actual pointer as a pointer, i.e. a pointer to a pointer:
void my_function(char **a)
{
*a = NULL;
}
Use the address-of operator `&` when you call the function to get the address of the pointer:
my_function(&ptr);
Problem
I am misunderstanding something basic about pointers in C, this should be simple but search brings up nothing. I do not understand the behaviour of the following code; ``` #include <stdlib.h> #include <stdio.h> void my_function(char *); int main(int argc, char *argv[]) { char *ptr; ptr = malloc(10); if(ptr != NULL) printf("FIRST TEST: ptr is not null\n"); else printf("FIRST TEST: ptr is null\n"); my_function(ptr); if(ptr != NULL) printf("SECOND TEST: ptr is not null\n"); else printf("SECOND TEST: ptr is null\n"); } void my_function(char *a) { a = NULL; } ``` Which outputs; ``` FIRST TEST: ptr is not null SECOND TEST: ptr is not null ``` Why does the second test still see the pointer as not NULL? I am trying to use a NULL pointer assignment as a sort of 'return flag' to indicate a certain failure of the function. But upon testing the pointer afterwards, it does not seem to be NULL.