8

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); } 
2
  • 12
    did you get a warning about a multi-character constant? You're using the wrong slash its '\0' not '/0' Commented Aug 12, 2012 at 2:42
  • declare forward_length as register class might also sometimes be useful. Commented Aug 13, 2012 at 6:44

4 Answers 4

24

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.

Sign up to request clarification or add additional context in comments.

Comments

15

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

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

Comments

9

To make this complete: while others now solved your problem :) I would like to give you a piece of good advice: don't reinvent the wheel.

size_t forward_length = strlen(forward); 

3 Comments

How does on use this size_t logic?
@vkaul11 What do you mean by "using this size_t logic"?
@H2CO3 Sorry,But It is always a good practice to write code for predefined functions
7

Your '/0' should be '\0' .. you got the slash reversed/leaning the wrong way. Your while should look like:

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

though the != '\0' part of your expression is optional here since the loop will continue as long as it evaluates to non-zero (null is considered zero and will terminate the loop).

All "special" characters (i.e., escape sequences for non-printable characters) use a backward slash, such as tab '\t', or newline '\n', and the same for null '\0' so it's easy to remember.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.