You're incrementing the pointer, but outputting the address of the variable that holds the pointer itself (&ptr
). You should output just ptr
(and format it accordingly - see edit below).
Example:
#include <iostream>
int main() {
char data;
char *ptr = &data;
std::cout << "pointer:" << (unsigned long long)ptr << std::endl;
ptr++;
std::cout << "pointer incremented: " << (unsigned long long)ptr << std::endl;
}
Output:
pointer:140732831185615
pointer incremented: 140732831185616
Yes, printing just ptr
will output garbage, so I converted the pointer to an integer (since pointers are memory addresses anyway).
As suggested in the comments, you can cast the pointer to void *
when printing, which gives nicer formatting:
pointer:0x7ffee5467acf
pointer incremented: 0x7ffee5467ad0
Note how 0x7ffee5467acf == 140732745022159 != 140732831185615
- you'll get different outputs on each run because the kernel will load the executable into different places in memory.
EDIT: yes, the first version of this answer, about simply outputting ptr
with std::cout << ptr
, was incorrect, because the <<
operator is overloaded in such a way that it treats pointers to char
as C-strings. Thus, that version would access potentially invalid memory and output garbage.
But the concept remains the same. Pointers to int
, for example, don't have this "problem" and are printed as hexadecimal numbers, even without casting them to void *
: Try it online!. The output shows that pointers are still incremented correctly by sizeof(int)
, which equals 4 on that machine.