Sato Sato - 2 months ago 23
C Question

Should I manually allocate string ending char '\0' in c?

I'm new to c, and confused by string ending char '\0', should I allocate it?

for example, I want to store a string with a max length of 6;

If I use array, should I use

char str[6]
or
char str[7]
?

char as[3] = "abc";
printf("%s\n", as);
//seems no problem


If I use char pointer, should I use
char *str = malloc(6)
or
char *str = malloc(7)
?

Answer Source

For an array that is pre-initialized, you don't need to write a number in the brackets. You can just write

char str[] = "this is my string";

And the compiler will automatically calculate the number of bytes needed.

But for malloc, you must add 1. Ex:

char *strdup(const char *str)
{
    char *ret = malloc(strlen(str) + 1);
    strcpy(ret, str);

    return ret;
}