what is the difference between char **str and char *str[] in C?

int main(void){
   char **str = (char **)malloc(5 * sizeof(char*));
   char *str2[5];

   str[1] = "hello";
   str2[1] = "hello";

   printf("%s\n", str[1]);
   printf("%s\n", str2[1]);

the output is the same.

and how can a function return char *str[]?

1 Answer 1


For some fun,

printf("str  %016p  &str  %016p\n", str, &str);
printf("str2 %016p  &str2 %016p\n", str2, &str2);

Second line gives surprising output, doesn't it?

Other than that, not much of a difference. One stores the array on heap, the other on stack. That's also the problem in returning: If you allocate on stack (like char *str2[5]), and exit the block where the variable got declared, it no longer exists. The values remain there, but the memory is interpreted as unused and will be used for the next variable declared on stack.

If you want to return such thing, either have it created in the calling function and pass a pointer (so that it never leaves the block it got declared in), or allocate it on heap.

  • Program prints error: flag '0' results in undefined behavior with 'p' conversion specifier [-Werror,-Wformat] printf("str2 %016p &str2 %016p\n", str2, &str2); when I try your "for some fun" code. Dec 13, 2018 at 16:39
  • @NikitaKokorin %016p worked for me, using non-standard formatting of the memory address (I wasn't aware it's non-standard, that's why you get an error, your compiler does not like it). If it does not compile for you, you could change to just %p, or pick any suggested solution from stackoverflow.com/questions/1255099/…
    – Blauelf
    Dec 13, 2018 at 16:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .