C Pointer Arithmetic size (struct)

Here is the code in question

#include <stdio.h> struct test { unsigned char t; unsigned short u; unsigned char v; }; int main () { struct test * a = (void *) 0x1000; printf("%x %p %p\n", sizeof(struct test), a + sizeof(struct test), a - sizeof(struct test)); return 0; } 

The file sizeof (struct test) prints 6, so I expect to see:

6 0xffa 0x1006

Instead i get

 6 0x1024 0xfdc 

The last time I checked, 0x24 or 36, was not equal to 6. It did not even equal anything that I can say. I will completely lose.

Can someone explain to me why I get these values?

+7
source share
4 answers

The problem is that when you do pointer arithmetic, it increases by a few of the size of the data type.

So what you do is add a square sizeof(struct test) .

Since sizeof(struct test) = 6 , you increase the address by 6 * 6 = 36 . Therefore, you get 0x1024 and 0xfdc instead of 0x1006 and 0xffa . (You also switched + and - , but this is a trifle.)

Instead, simply do the following:

 printf("%x %p %p\n", sizeof(struct test), a + 1, a - 1); 
+16
source

When you perform such pointer arithmetic, you move forward or backward with this number of elements, as if this variable were in an array. So you really want to just use a + 1 and a - 1 , which should each increase by 6 bytes.

IMPORTANT: Keep in mind that the compiler can add an addition to your structure to help with alignment. Don't just assume that since you have two single-byte characters and a double-byte short that your structure will be 4 bytes in size - this is not the case here. (Actually, don't assume that you know char size or short, I saw 2-byte characters before).

+4
source

I think you are looking for a + 1 and a - 1 .

(a + x) the same as &a[x] .

+2
source

You have an entered pointer.

So, when you increment it by 1 (i.e. a + 1 ), that means a + sizeof(type) .

So a + sizeof(type) = a + sizeof(type) * sizeof(type) = a + 6 * 6 (in your case, as sizeof (test) = 6)

What do you get 0x24 or 36 of.

+1
source

All Articles