1

I'm looking through some code for learning purposes. I'm working through this portion of code.

// e.g. const unsigned char data={0x1,0x7C ... }
unsigned char buf[40];
memset(buf,0,40);
buf[0] = 0x52;
memcpy(buf+1, data, length); // What does buf+1 do in this situation?

On the last line where memcpy is called what does buf+1 do? buf is a character array, so what does +1 do to it?

joshwbrick
  • 5,882
  • 9
  • 48
  • 72

4 Answers4

5

buf+1 is equivalent to &(buf[1])

rpetrich
  • 32,196
  • 6
  • 66
  • 89
4

In C, every array name is a pointer, so buf here also means the pointer which point to buf[0].Then "buf+1" means "buf[1]"'s address.

zxeoc
  • 76
  • 1
  • Ah cool. I had a hunch that was what it was doing, but the syntax did make sense to me. Thanks for clearing that up for me! – joshwbrick Sep 08 '09 at 01:54
  • 4
    More correctly, if an array is used in an expression where it isn't the subject of the `sizeof` or `&` operator, it evaluates to a pointer to its first element. – caf Sep 08 '09 at 01:56
3

buf+1 is the same as &(buf[1]). In other words, it returns a pointer to the 2nd (index 1) character of buf.

derobert
  • 49,731
  • 15
  • 94
  • 124
0

Pointer Arithmetic (Stack Overflow)

Community
  • 1
  • 1
Andrew Keeton
  • 22,195
  • 6
  • 45
  • 72