an0nh4x0r an0nh4x0r - 3 months ago 17
C++ Question

Pointers, sizeof() and address in C++

This is the program

int main() {
cout << sizeof(int) << endl; // for int its 4 in g++ compiler

int *p;
int a = 5;
p = &a;
cout << "The value of p is: " << p << endl;
cout << "The value of p + integer is: " << p + 0 << endl;

// lets take the size of individual 1, 2, 3
cout << "The sizeof(0) is: " << sizeof(0) << endl; // 4
cout << "The sizeof(1) is: " << sizeof(1) << endl; // 4
cout << "The sizeof(2) is: " << sizeof(2) << endl; // 4

cout << "The value of p + 0 is: " << p + 0 << endl;
cout << "The value of p + 1 is: " << p + 1 << endl;
cout << "The value of p + 2 is: " << p + 2 << endl;

return 0;
}


The
sizeof()
function in C++ gives
sizeof(int)
4 bytes, in
g++
compiler. So I printed the
sizeof(1)
,
sizeof(2)
,
sizeof(0)
to terminal and I got 4 bytes.

So I tried some pointer arithmetic in the program in above link. I added 1 to a pointer variable. Let's say
int *p; int a = 10;
. Now I assigned
p = &a;
. Now when I printed
p
it gives
0x24fe04
and when I printed
p + 0
it's the same. But when I tried adding
p + 1
and
p + 2
it gives different output like this:
0x24fe08
,
0x24fe0c
respectively. Please help me understanding this arithmetic. Why
p+1
,
p+2
is not equal as in address it's contributing the same 4 bytes.

snr snr
Answer

When you are saying p + 1, meaning that p + 1 * sizeof(int). As I've mentioned here, the formula is