Reputation: 8602
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)
?
Upvotes: 2
Views: 118
Reputation: 18503
In addition to stackptr's answer:
If you are planning to overwrite your array:
char str[30] = "abc";
...
strcpy(str, "Hello world"); /* This will overwrite the content of "str" */
... the length of the array must be the maximum length of the string plus 1.
In the example above you may write strings of up to 29 characters length to the array.
Note that the following definition:
char str[] = "abc";
... implicitly creates an array of 4 characters length so you are limit to 3 characters.
Upvotes: 0
Reputation: 98
You should be using string length + 1. In your case you must use 7 while declaring the char array. The example you provided would have worked because of the undefined behaviour shown by printf().
Upvotes: 0
Reputation: 11237
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;
}
Upvotes: 3