I want to use a local pointer to point to a global string. The pointer is a local pointer and the string is global. When I run this code passing the local pointer to the function “myfun” the pointer is not changed, i.e., its pointing address does not change. The values printed are “NULL”.
Can someone tell me why this does not work on gcc?
#include <stdio.h>
char *str[] = { "String #1", "Another string" };
void myfun( void * p, int i )
{
p = ( void * ) &str[ i ][ 0 ];
}
int main( void )
{
void * ptr1, * ptr2;
myfun( ptr1, 0 );
myfun( ptr2, 1 );
printf( "%s\n%s\n", ptr1, ptr2 );
}
You are passing a pointer, by value, to
myfun. The value you assign topinmyfunis therefore not returned to the caller. You need to pass a pointer to the pointer:And call it like this:
In fact you can write
myfunlike this:And in fact it would be simplest just to return the
void*as the functions return value: