I was just trying to see how to check for the null terminating character in the char *
array but I failed. I can find the length using the for
loop procedure where you keep on checking each element, but I wanted to just use the while
loop and find the null terminating string. I never seem to exit the while
loop. Any reason why this is so?
char* forward = "What is up";
int forward_length = 0;
while (*(forward++)!='/0') {
forward_length++;
printf("Character %d", forward_length);
}
char arrays are not automatically NULL terminated, only string literals, e.g. char *myArr = "string literal"; , and some string char pointers returned from stdlib string methods.
or cast char letterChar into an int and check if it equals 0 since the default value of a char is \u0000 - (the nul character on the ascii table, not the null reference which is what you are checking for when you say letterChar == null )- which when cast will be 0 .
The null character indicates the end of the string. Such strings are called null-terminated strings. The null terminator of a multibyte string consists of one byte whose value is 0. The null terminator of a wide-character string consists of one gl_wchar_t character whose value is 0.
The null terminated strings are basically a sequence of characters, and the last element is one null character (denoted by '\0'). When we write some string using double quotes (“…”), then it is converted into null terminated strings by the compiler.
You have used '/0'
instead of '\0'
. This is incorrect: the '\0'
is a null character, while '/0'
is a multicharacter literal.
Moreover, in C it is OK to skip a zero in your condition:
while (*(forward++)) {
...
}
is a valid way to check character, integer, pointer, etc. for being zero.
The null character is '\0'
, not '/0'
.
while (*(forward++) != '\0')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With