Marsil
Marsil

Reputation: 13

Local pointer to a global function

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

Upvotes: 1

Views: 506

Answers (2)

Happy Green Kid Naps
Happy Green Kid Naps

Reputation: 1673

Fundamentally, your question isn't any different from -

void func(int i)
{
  i = 2;
}

int main()
{
  int i = 0;
  printf("i = %d\n", i);
  func(i);
  printf("i = %d\n", i); /* Wonder why it doesn't output i = 2? */
}

In your code, you pass ptr1 (and ptr2) arguments by value, change the value of the parameter p that you receive, and expect this change to be reflected on the argument that you passed. That, that ptr1 and ptr2 are pointers doesn't change the fact that you are still passing by value.

Also, IANAL (i.e., I hope a language lawyer corrects me if I am wrong), but I think you are potentially headed for trouble by sending pointer to void variables as arguments to printf.

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612954

You are passing a pointer, by value, to myfun. The value you assign to p in myfun is therefore not returned to the caller. You need to pass a pointer to the pointer:

void myfun( void ** p, int i ) 
{ 
    *p = ( void * ) &str[ i ][ 0 ]; 
}

And call it like this:

myfun( &ptr1, 0 ); 

In fact you can write myfun like this:

void myfun( void ** p, int i ) 
{ 
    *p = str[i]; 
}

And in fact it would be simplest just to return the void* as the functions return value:

void *myfun( int i ) 
{ 
    return str[i]; 
}

Upvotes: 5

Related Questions