Click here to Skip to main content
15,510,771 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
1)how (s[i]!=0) evaluates?
2)how does *(s+i) works?
3) how does i[s] works?
please help me with these douts

What I have tried:

int main()
    char s[]="peak";
    int i=0;
        printf("%c%c \n",s[i],*(s+i));
        printf("%c%c \n",i[s],*(i+s));
    return 0;
Updated 24-Jun-22 12:36pm

1 solution

C doesn't have any concept of strings past "string literal": a sequence of characters enclosed in double quotes.

So when you are traversing a char array, you need to know either how long the string is, or look for a string terminator character. C chose the latter: and selected the character '\0' as the terminator.
This is a null value which evaluates to zero when you try to use it in any form of math, including comparisons.
So s[i] != 0 is looking for the terminating character: the end of the string.

In C, the name of an array is defined as a pointer to the first element in the array, so *(s + i) adds the value of i to the address of the first element, and accesses that element: it's the equivalent of s[i]

i[s] doesn't even compile ... it's meaningless garbage.
Share this answer
k5054 24-Jun-22 23:40pm    
"i[s] doesn't even compile ... it's meaningless garbage."
Not true. In C and C++ 5[x] is perfectly valid, as is explained here:

I should add that except for lecture notes, trying it for yourself, obfuscated programming contests, and just someone being a right git, you should never see this usage in real life.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900