Check for null trailing char in char *

I was just trying to see how to check for a null terminating character in an array char *, but I failed. I can find the length using a loop procedure forwhere you keep checking every element, but I just wanted to use a loop whileand find the null ending line. It seems like I never leave the loop while. 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);
}
+5
source share
4 answers

You used '/0'instead '\0'. This is not true: a character '\0'is a null character, but '/0'a multi-channel literal.

Also, in C, it's ok to skip zero in your state:

while (*(forward++)) {
    ...
}

, , .. , .

+23

'\0', '/0'.

while (*(forward++) != '\0')
+14

'/0' '\0'.. , /. while :

while (*(forward++)!='\0') 

!= '\0' , , ( ).

"" (.. escape- ) , ​​ '\t', newline '\n', null '\0', .

+6

To make it complete: while others have now solved your problem :) I would like to give you good advice: do not reinvent the wheel.

size_t forward_length = strlen(forward);
+6
source

All Articles