Search code examples
carrayspointerspointer-to-pointer

C: Array of pointers vs pointer-to-pointer


Do these two pieces of C code achieve the same goal:

char ** p;
p = malloc(sizeof(char*) * 10);

--------------------------------

char * z[10];

It seems like they can be used identically:

p[1] = "Foo";
*(p+2) = "Bar";

---------------------

z[1] = "Foo";
*(z+2) = "Bar";

Is there a difference?


Solution

  • If you just store and retrieve values from the array, or malloc-allocated area, they work the same.

    There are differences, though. sizeof and & work differently, you need to explicitly free the malloc-allocated area to release the memory, and you can change its size with realloc.