-1

I have a function that declares an array of chars and then assigns a value to it and then the decayed pointer is passed to another func like this pseudo c code, so that if I do printf("country %s," country) inside anotherfunc it gives me "GERMANY"

void somefunc()
{
...
char *country = NULL;
country = "GERMANY"
...

anotherfunc(country); //printf("country %s," country)` == GERMANY
}

How do I move the call to anotherfunc outside of somefunc and still be able to pass the country char array? Right now, printf("country %s," country) is giving me (null)

char *country = NULL; // declare country outside both somefunc and anotherfunc

somefunc(country); //"GERMANY" is assigned inside somefunc

//if I do `printf("country %s," country)` it is `(null)`
//so "GERMANY" is not available inside another func

anotherfunc(country);
Leahcim
  • 40,649
  • 59
  • 195
  • 334

1 Answers1

1

Pass a pointer to a pointer:

void somefunc(char **pcountry) {
  *pcountry = "GERMANY";
}

and call it

somefunc(&country);
Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
  • for completeness, then what do I pass to anotherfunc and please show the call of somefunc, like this `somefunc(&country)`? – Leahcim Mar 06 '17 at 19:27
  • That's what I did but it's still null, do I declare it `char *country` or `char **country`? – Leahcim Mar 06 '17 at 19:33
  • 1
  • ok, thank you very much. I'll accept your answer in 34 seconds once SO lets me. – Leahcim Mar 06 '17 at 19:38
  • I'm getting a warning from the compiler using the code from your answer-- `incompatible pointer types passing `char ***` to parameter of type 'char **'` I declare country like this: `char **country = NULL;` and then pass it `somefunc(&country) anotherfunc(&country)`. The signature of `anotherfunc` and `somefunc` are like this `somefunc( char**country)` Note, I'll keep your answer as accepted for now, because I assume I'm doing something wrong ! Thanks again. – Leahcim Mar 07 '17 at 14:13
  • Yes you are doing something wrong. – Jean-Baptiste Yunès Mar 07 '17 at 16:10
  • ok, thank you, can you tell me what I'm doing wrong, or is it not clear from my comment? or is it outside the scope of the question? – Leahcim Mar 07 '17 at 16:29
  • I posted another question with a link to sample code regarding this error. I don't think I'm doing something wrong. http://stackoverflow.com/questions/42654861/compiler-recommendation-leads-to-seg-fault – Leahcim Mar 07 '17 at 17:46