0

I recently came across the following code on stack overflow (see the whole post here):-

char *c = "200939915";
char *d = c + 1;

It assigns d a value of "00939915", which I find very counter-intuitive.

Can someone explain the mechanism of the process? What is this thing called?

I am a freshman and doing Introductory CS courses, so this would be of great help:)

Community
  • 1
  • 1
aditya
  • 43
  • 5
  • What does your course textbook say? What did a Google search reveal? These questions have been answered before, so you should be able to find the answer. – AntonH Feb 09 '17 at 16:16
  • 1
    `d` is a pointer that points to the second character in the array pointed to by `c` (`c[1]`), whereas `c` points to the first element (`c[0]`). So if you print `d`, naturally it'll start from the second character – Alex Feb 09 '17 at 16:16
  • 2
    @AntonH I tried finding it on stackoverflow, but have no idea what to search (ie. its name). – aditya Feb 09 '17 at 16:18
  • 2
    @aditya You're know you're working with pointers, and you're adding a value. I literally entered "pointer add" in Google. It auto-completed to "pointer addition", and resulted in many responses for "pointer addition" and "pointer arithmetic". Less than 30 seconds to find a slew of help directly on Google. – AntonH Feb 09 '17 at 16:20

4 Answers4

7
char *c = "200939915";

Here c is a pointer to a char(The first char of 200939915). c+1 will point to the next char.

          (2 0 0 9 3 9 9 1 5)
           ^ ^
           | |
           c c+1
Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34
2

d does not "contain" the value you said. d is a pointer to a char and by setting it to c+1 it points (contains the memory address) to the second element of the string literal you declared.

I guess you did something like this printf("%s",d); this leads to printf reading the memory starting from the position d points to and output every character in there until it catches a '\0' (end of string) and then finish.

It does not truncate your string you just start reading it at another position.

Kami Kaze
  • 2,069
  • 15
  • 27
1

c[0] = 2 c[1] = 0 c[2] = 0 c[3] = 9 and so on. c is the address of that first character, 2. So d is the address c + 1 more, therefore the address of the first 0 in this case.

donjuedo
  • 2,475
  • 18
  • 28
1

As @Gaurav Sehgal pointed out, your variables only point to strings of characters, not numbers. What would you expect the value of d to be here:

 char *c = "abcdefghi";
 char *d = c + 1;
FredK
  • 4,094
  • 1
  • 9
  • 11