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); 
5
  • 1
    in short: yes... (it's const char*) Commented Jan 17, 2014 at 12:38
  • @KarolyHorvath In C it is char[N] Commented Jan 17, 2014 at 12:40
  • @GrijeshChauhan: no, it's a string literal which cannot be modified. Commented Jan 17, 2014 at 12:44
  • Yes its kind the same, but how could I reach that question? Anyway, thx about your answers! Commented Jan 17, 2014 at 12:45
  • @KarolyHorvath Yes my comment was for string literal, in C type of string literal is char[N] try it e.g. apply sizeof code. of-course in C++ type of string literal is const char*. Commented Jan 17, 2014 at 13:15

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.