-1

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?

Victor Brunell
  • 5,668
  • 10
  • 30
  • 46

3 Answers3

2

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.

Thomas Padron-McCarthy
  • 27,232
  • 8
  • 51
  • 75
0

in terms of use and functionality, there really is no difference except in how you plan to use it.

An example of what I mean is that I could use a double pointer for iterating and dereferencing the whole multidim array.

not to mention that when you malloc, you need a matching free when you're done with it.

Of course, you should only malloc when you think you really need it or you need a massive amount of memory.

Last part I want to say is that with the pointer array, you cannot dereference the individual characters without using the subscript operator []

Nergal
  • 349
  • 3
  • 14
-1

C memory is split into several types, stacks -for function calls and local variables, and then there is heap -for malloced objects. The stack usually has smaller size than the heap. As a result, if you try to allocate a huge array in stack you might exceed the stack's storage space causing segfault.

In this case when you malloc an array, heap memory is being used .And it will exist until it is explicitly deallocated with free. This is useful in cases where you are using large array size. Whereas in the first case you are declaring the array in stack,which lives only as long as the function that calls it exists.

Since the array size is small here, both works. But for larger arrays, malloc'ing is recommended to avoid segfault.

megha
  • 67
  • 1
  • 5