0

I have such code:

char str1[100] = "Hel0lo";
char *p;
for (p = str1; *p != 0; p++) {
    cout << *p << endl; 
    /* skip along till the end */ 
}

and there are some parts not clear for me. I understand that null-terminated string at memory is byte with all bits equal to 0 (ASCII). That's why when *p != 0 we decide that we found the end of the string. If I would like to search till zero char, I should compare with 48, which is DEC representation of 0 according to ASCII at memory.

But why while access to memory we use HEX numbers and for comparison we use DEC numbers?

Is it possible to compare "\0" as the end of string? Something like this(not working):

for (p = str1; *p != "\0"; p++) {

And as I understand "\48" is equal to 0?

Viacheslav Kondratiuk
  • 8,493
  • 9
  • 49
  • 81

2 Answers2

2

Your loop includes the exit test

*p != "\0"

This takes the value of the char p, promotes it to int then compares this against the address of the string literal "\0". I think you meant to compare against the nul character '\0' instead

*p != '\0'

Regarding comparison against hex, decimal or octal values - there are no set rules, you can use them interchangably but should try to use whatever seems makes your code easiest to read. People often use hex along with bitwise operations or when handling binary data. Remember however that '0' is identical to 48, x30 and '\060' but different from '\0'.

simonc
  • 41,632
  • 12
  • 85
  • 103
2

Yes you can compare end of string like:

for (p = str1; *p != '\0'; p++) {
        // your code 
}

ASCII value of \0 char is 0 (zero)

you Could just do

for (p = str1; *p ; p++) {
        // your code 
}

As @Whozraig also commented, because *p is \0 and ASCII value is 0 that is false

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208