user834697
user834697

Reputation: 235

this size to use into malloc() is right?

Assuming that I have char ** where each value of can have an char * and I need store more bytes to character teminator (NULL) how do I to compute this size? maybe..: sizeof(char *) * strlen(src) + sizeof(NULL) or only + 1 instead of sizeof(NULL)? I hope this is clear for you. Thanks in advance.

Upvotes: 0

Views: 170

Answers (1)

AerandiR
AerandiR

Reputation: 5470

A char ** is a pointer to a pointer to the first character of a string. In your example, the memory for the pointer char **out is already allocated on the stack. What you have to do is allocate the memory for the character array (C string) which out points to on the heap. That is, you could do something like:

char **out;
char *str = malloc(strlen(src) * sizeof(char) + 1);
*out = str;

Now you can (for example) safely return out and pass control of the memory you allocated to the caller.

If you wanted to return a pointer to the first element of an array of strings (another way of interpreting a char **), you would have to first allocate on the heap enough memory for each string:

char **out = malloc(amount_of_strings * sizeof(char *));
// Repeat the following for each string in your array...
char *str = malloc(strlen(src) * sizeof(char) + 1);
out[index] = str;

Upvotes: 1

Related Questions