Question

I have the method...

char** getStrings(); which will return a pointer to char pointers.

is it possible to do ..

char** allStrings = getStrings()?

or must I do something like...

char** alStrings = malloc(sizeof(char*) * numberOfStrings);
allStrings = getStrings()
//where numberOfStrings is some int.
Was it helpful?

Solution

The first one is obviously correct.
The second one, after fixing the typo, is equal to the first one plus a memory leak.

Please also refer to the functions contract for accessing all those strings, and for deallocation.

You probably get a NULL-terminated array of 0-terminated strings, but deallocation might be trickier.

Likely deallocation choices:

  • Static data, trap for multithreading/recursion/multi-call trap, no explicit deallocation needed nor permissible.
  • All in one block, only free the main pointer.
  • Each component must be freed separately.

OTHER TIPS

If getStrings() does the allocation for you, then of course char **allStrings = getStrings() is fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top