I know in C '\0'
is always at the end of a string, but is '\0'
always mark the end of a string?
Just like "1230123" can be recognized as "123"?
One edition of the question used the notation '/0'
instead of '\0'
.
I know in C '\0'
is always at the end of a string, but is '\0'
always mark the end of a string?
Just like "1230123" can be recognized as "123"?
One edition of the question used the notation '/0'
instead of '\0'
.
A byte with the value 0 by definition marks the end of a string. So if you had something like this:
char s[] = { 'a', 'b', 'c', '\0', 'd', 'e', 'f', '\0' };
printf("%s\n");
It would print abc
.
This is different from "1230123"
where the 4th character in the string is not the value 0 but the character '0'
, which has an ASCII code of 48.
The null terminating character is represented as \0
and not /0
and it always mark end of string because, in C, strings are actually one-dimensional array of characters terminated by a null character \0
.
This
char s[] = "1230123";
is same as this
char s[] = {'1', '2', '3', '0', '1', '2', '3', '\0'};
| |
This is character '0' |
whose decimal value is 48 |
|
This is null terminating character
whose decimal value is 0
Check this example:
#include <stdio.h>
int main (void)
{
int x,y,z;
char s1[] = "1230123";
char s2[] = {'1','2','3','\0','4','5','6','\0'};
printf ("%s\n", s1);
printf ("%s\n", s2);
return 0;
}
Output:
1230123
123 <======= The characters after null terminating character is not printed.
A string literal can have a '\0'
in the middle.
A string only has a '\0'
at the end.
'\0'
is the null character and has a value of 0. '0'
is the character zero.
See value of '\0' is same ... 0?
C has, as part of the language, string literals.
The two string literals below have a size of 8: the 7 you see plus the 1 not explicitly coded trailing null character '\0'
.
"abc-xyz" // size 8
"abc\0xyz" // size 8
C, as part of the standard library, defines a string.
A string is a contiguous sequence of characters terminated by and including the first null character.
Many str...()
functions only work with the data up to the first null character.
strlen("abc-xyz") --> 7
strlen("abc\0xyz") --> 3