Viacheslav Kondratiuk
Viacheslav Kondratiuk

Reputation: 8879

Representation of C string at memory and comparison

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?

Upvotes: 0

Views: 547

Answers (2)

simonc
simonc

Reputation: 42175

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'.

Upvotes: 2

Grijesh Chauhan
Grijesh Chauhan

Reputation: 58271

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

Upvotes: 2

Related Questions