string - passing address of variable to a C function -


i'm relatively new c. i'm trying pass address of variable function, , have function assign char pointer variable address passed. compiler doesn't complain, code doesn't work either.

typedef enum {     val_1,     val_2 } member_type;  char *a1="test 123";  int func (member_type x, char *temp) {      switch(x) {         case val_1:              temp = a1;              return 1;         case val_2:              return 2;     }     return 0; }  int main(){      member_type b;     static char *d1;     b = val_1;     printf("%p\n",&d1);      func(b, &d1);      printf("val_1:%s\n",d1);      return 0; } 

i following error when execute it:

-bash-3.00$ ./a.out  0x500950  name:(null) 

can me how fix it?

i find strange compiler doesn't complain. suspect compiling without warnings. should compile using -wall option enabled (assuming using gcc or clang).

what doing wrong although passing address of char * pointer function, modify local copy of pointer (function arguments passed value in c), has no effect outside function. should declare function argument pointer-to-pointer, , modify original pointer dereferencing address:

void func(const char **p) // notice pointer-to-pointer... {     *p = "bar"; // , dereference (*) operator }  const char *p = "foo"; printf("before: %s\n", p); func(&p); printf("after: %s\n", p); 

this prints:

before: foo afte: bar 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -