Confusion with C Strings

Please explain me this code step by step
  char s[] = "hello"; // s here means string
  for(char *cp = s; *cp != 0; cp++){ //cp here means character string
  printf("char is %c \n", *cp)

What I've figured out till now is :
1. We are creating a string array called s whose values is hello.
2. In line 2 we are creating a string pointer called cp whose address is s. Now if the value of s is not zero, then we are printing the given statement. then we are incrementing cp pointer (not the value of s, but only the pointer's value).
3. "char is" gets printed and %c is replaced with a character whose value is that s.

my queries:
1. what is the value of s in first place?!
2. how is output giving me the individual characters of "hello"?

PLEASE PLEASE PLEASE explain me this thing step by step :-)

Thank you in advance
The code has comments which are inaccurate or misleading. Corrected below:
    char s[] = "hello"; // s here means array of characters
    for (char *cp = s; *cp != 0; cp++) // cp here means pointer to a character
          printf("char is %c \n", *cp);

The initial contents of the array s is
{ 'h', 'e', 'l', 'l', 'o', '\0'}
That is the array is 6 characters in length, the first element is the letter 'h' and the last element is zero, sometimes represented as the character '\0'.

If we interpret the array as a character string, then the zero marks the end of the string.

The for loop uses the pointer char * cp which is set to point to the first element of the array, which is the letter 'h'.

The printf statement uses the %c code which is used to print the single character pointed to by cp. The loop increments the pointer cp to step through the array (or string) one character at a time. When the value pointed to is equal to 0 the loop terminates.
Last edited on
I'd totally forgotten about the null terminator! Thank you sir! You saved me from failing a test tomorrow!
Topic archived. No new replies allowed.