Click to See Complete Forum and Search --> : Memory allocation in C


Pinball
10-25-2001, 05:18 PM
This may be really silly, but I don't seem to make any progress towards the answer. This is the thing:
let's say I want to allocate a char array: (array[] = "Hellow"), by calling calloc. Now do I need to ask calloc for 6 o 7 objects of size char?
I do want to have space for the null terminator '\0':
for example:

char array[] = "hellow";
char *str;

str = calloc(strlen(array)+1, sizeof(char));

/* is the strlen(array)+1 ok? */
/* or should it be just (strlen(array) */

Thanks, for any directions here...

kmj
10-25-2001, 05:22 PM
strlen returns the number of characters, not including the null terminator, so if you want to have a string of the same length as another one, you'll need to add space for the null terminator. so yeah, do it with the '+1'.

Pinball
10-25-2001, 11:10 PM
OK, THANKS!... Couldn't figure that out.

kmj
10-25-2001, 11:11 PM
sure :)