1

I saw this statement of printf

printf("Hello printf\n" +6);

and when I run it I got this: printf. Its the 1st time I saw this version of printf without , after the "". Shall I think the above command, as below?

char *p = "Hello printf";
printf("%s\n", p+6);
yaylitzis
  • 5,354
  • 17
  • 62
  • 107

3 Answers3

4

It's called pointer arithmetic. What it does is take the pointer to the string literal, and add six "units" (where a unit is the size of the underlying type pointed to, in this case sizeof(char) (which always is one)).

You can see the string like this:

 +--+--+--+--+--+--+--+--+--+--+--+--+--+
 | H| e| l| l| o|  | p| r| i| n| t| f|\0|
 +--+--+--+--+--+--+--+--+--+--+--+--+--+
 0  1  2  3  4  5  6  7  8  9 10 11 12 13

The numbers below is the offset, or index if using array notation, to the specific letter in the string.

The important thing to know here is that it doesn't add bytes, it's just a coincidence here because the base type is the size of a byte. If you had an array of short (which is usually two bytes) then adding six would add 6 * sizeof(short) bytes, that is in the normal case 12 bytes.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 1
    I am not sure if "the size of the pointer type" is the best description. Size of the pointer type is `sizeof(*void)` or `sizeof(int)` most usually. Maybe "size of the pointed type", or "underlying type". Not sure what you think about it. – luk32 Jan 17 '14 at 12:44
3

Yes, you got it right: you are incrementing the pointer from the beginning of the string before printing it.

By the way, your char* should be const char* if you want to store a pointer to a literal string like that.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
0

The string literal "Hello printf" is a const character array. When you use it you get the address of the first character. The +6 is simple pointer arithmetic.

Yes, the two lines give the same command. When you use an optimizing compiler that eliminates the local variable you have a good chance to get the same compiler output.

harper
  • 13,345
  • 8
  • 56
  • 105