0
#include<stdio.h>
#include<cs50.h>

void test(char* msg)
{
    puts(msg+6);
}

int main(void)
{
    char* msg ="HelloWorld";
    test(msg);
    return 0;
}

Here since char pointer points to address of H.The output must be W but I don't understand why it shows World even though we are not using pointer arithmetic like *(msg+i) in a loop.

1

It really is pointer arithmetic. Try printf("%c\n",*(msg+6)); to see the difference. You'd have to use printf because the argument to puts is a const char*, and the result of *(msg + 6) is a char.

*(msg + 6) says "show me the contents at the 6th byte of msg" (dereference it) while msg + 6 says "show me the contents of msg starting at the 6th byte."

11
  • Ok.But I don't really understand how (msg+6) outputs all characters from 6th byte.
    – qwerty
    Dec 1 '16 at 17:03
  • It is the syntax of the C language. That's what the compiler "creates" when it sees that notation. An idiom, if you will. The same way it would output 7 if you said printf("%i\n",3 + 4); Dec 1 '16 at 17:11
  • I mean if we use char* a="hello"; a points to address of h right?
    – qwerty
    Dec 1 '16 at 17:17
  • Then why does it print hello if we use printf ("%s",a); even if it is not an array?
    – qwerty
    Dec 1 '16 at 17:21
  • char* is a pointer to an array of chars. Dec 1 '16 at 17:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .