Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check the null terminating character in char*

Tags:

c

string

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);
}
like image 790
vkaul11 Avatar asked Aug 12 '12 02:08

vkaul11


People also ask

Are all char * null-terminated?

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.

How do you check if a character is null?

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 .

What is null termination character?

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.

What is the null terminating character in C?

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.


2 Answers

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.

like image 142
Sergey Kalinichenko Avatar answered Sep 23 '22 11:09

Sergey Kalinichenko


The null character is '\0', not '/0'.

while (*(forward++) != '\0')
like image 30
pb2q Avatar answered Sep 22 '22 11:09

pb2q