Reputation: 93
I think a
totally equals b
. But the result of running proves me wrong. Which part do I understand in the wrong way?
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char a[] = "abcdefg";
char b[] = {'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g'};
printf("%s\n" , a);
printf("%s\n" , b);
system("pause");
return 0;
}
Upvotes: 0
Views: 114
Reputation: 16540
the printff for 'b' will fail as there is no string terminator '\0' at the end of the 'b' array.
The strings do not match because 'b' contains one less byte than 'a' as 'a contains the trailing '\0' needed to make it a string while 'b' is just an array of bytes.
Upvotes: 0
Reputation: 1227
Because a
is equal to char a[] = {'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g', '\0'};
.
printf()
will print character before '\0'
.
Upvotes: 1
Reputation: 3642
When the C compiler finds the following code
char a[] = "abcdefgh";
It actually sets aside enough memory to store 9 chars, the 8 that you have included in your string plus an extra char to hold a 0, the nul character. C uses the nul character to mark the end of a string. Without it, none of the C string functions would be able to tell where the end of a string was in memory.
The code
char b[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
tells C explicitly to reserve storage for 8 chars and to set them to the values you've given. There is no nul terminator specified (i.e. no 0 on the end) and so C functions won;t be able to tell how long this string is.
printf("%s\n" , a);
Tells C to print the string that it finds starting at address a in memory. It keeps printing characters until it finds the 0 terminator that the compiler quietly puts in for you.
printf("%s\n" , b);
Tells C to print the string that it finds starting at address b in memory. It keeps printing characters until it finds a 0 terminator but since you didn't put one in the array, it will carry on printing out whatever was in memory after the array you defined until it comes across a 0.
To fix this you need to explicitly tell the compiler to put a 0 after the other characters. You can do this using the special character \0 as follows:
char b[] = {'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g', '\0' };
Upvotes: 10
Reputation: 53016
The second printf()
statement is wrong because the array b
are not strings, since they have a missing nul
terminator.
Try like this
char b[] = {'x' , 'x' , 'x' , 'x' , 'x' , 'x' , 'x', '\0'};
Upvotes: 1