izotov said:
My question would be why gcc allows the form char abcd[4] = "abcd"; with no warning and why it seems to work as if it was char abcd[5] = "abcd";?
The
char abcd[5] = "abcd"; is not a string, it is an array.
When you create an array, and it is not initialized, the array will be filled random numbers (ie the fact that lying around in memory).
Code:
#define SIZE 3
...
char abcd[SIZE];
int i = 0;
for (; i < SIZE; ++i) {
printf("Code %d symbol: %d", i, (int)abcd[i]);
if (abcd[i] == '\0') printf(" (it is NULL symbol).\n");
else printf(".\n");
}
...
Result:
Code:
Code 0 symbol: 48.
Code 1 symbol: -38.
Code 2 symbol: -1.
When we initialize the array, it will be filled with zeros.
Code:
...
char abcd[SIZE] = "";
...
Result:
Code:
Code 0 symbol: 0 (it is NULL symbol).
Code 1 symbol: 0 (it is NULL symbol).
Code 2 symbol: 0 (it is NULL symbol).
When we initialize the array some data, the first array address these data, all the rest will be filled with zeros.
Code:
#define SIZE 5
...
char abcd[SIZE] = "abc";
...
Result:
Code:
Code 0 symbol: 97.
Code 1 symbol: 98.
Code 2 symbol: 99.
Code 3 symbol: 0 (it is NULL symbol).
Code 4 symbol: 0 (it is NULL symbol).
The
char abcd[5] = "abcd"; is not a string, it is array. A static array of
N elements has the starting address
0 and ending address
N-1. Your example is equivalent:
Code:
char abcd_1[SIZE] = "abc";
char abcd_2[SIZE] = {'a', 'b', 'c'};
int abcd_3[SIZE] = {97, 98, 99};
In your example
char abcd[5] = "abcd"; a null character at the end, because that is when initializing the entire array is filled with zeros. No,
cc does not appends a null character at the end. This is not a string.
The function
strlen(3) computes the length of the string is find a zero symbol. We'll see how it works.
Code:
char abc[5] = "1234";
printf("Size: %d\n", (int)strlen(abc));
So we have
abc[0]-abc [3] == 1 .. 4, and at the end of the array
abc[4], we have zero (it is there because when you first initialize the entire array has been filled with zeros).
Result:
It's true ... Let's fill the entire array.
Code:
char abc[5] = "12345";
printf("Size: %d\n", (int)strlen(abc));
Result:
Why 6? Why not 5? Because the array not has a null character at the end, the function of
strlen(3) misses and goes into the not initialized memory.
С has not strings, you can use a pointer to a memory. Use a static memory.
Code:
char *abc = "Hi, I am string!";
Use a dynamic memory. (P.S. See
malloc(3)/
free(3) and
strcpy(3))
Code:
char *abc = (char*)malloc(20*sizeof(char));
strcpy(abc, "Hi, I am string!");
...
free(abc);
Use a static buffer.
Code:
char buf[20];
char *abc = buf;
strcpy(abc, "Hi, I am string!");
In the second and third case, you do need to take care that you have enough space for a null character.
P.S. Sorry for my English, I hope it helped for you.