C / C ++ pointers, ptr + 1 = ptr + 1 byte or ptr + 1 * sizeof (pointer_type)?

Having

any_type *ptr = (any_type*)malloc(sizeof(any_type)*size);
my_ptr = ptr+1;
memcpy(dst, my_ptr, sizeof(any_type));

Will my_ptr point to 1 byte after ptr or sizeof(any_type)bytes after ptr? How alignment parameters can affect the response? Is this different for signed / unsigned types?

+3
source share
5 answers

Arithmetic of the pointer is performed by the size of the static type [*] of the pointer, so it effectively adds sizeof *ptr. Alignment of elements will be taken into account in the size of the object, as type alignment (filling at the end of the object).

struct test {
   int a;
   char b;
};

The size testwill not be 5 (assuming a 32-bit int) if the 4-byte type is aligned.

[*] , ++ , , :

struct base { int x; };
struct derived : base { int y; };
int main() {
   base * p = new derived[10];
   base * q = p+1;             // this does not point to the second `derived`!!!
}
+11
  • sizeof (any_type) ptr
  • malloc , .
  • /
+4

1 . , , , .

+4

When you see a pointer, try to forget that it has a scalar value. Think, instead, that a pointer is a kind of token that gives you access to an object that is stored in continuous space (in memory). If ptris a pointer that gives you access to the object at some (arbitrary) position, ptr+1and ptr-1will return pointers that give you access to its neighbors.

+2
source

For pointer arithmetic to work, you need to point to sizeof (any_type) + the base address.

+1
source

Source: https://habr.com/ru/post/1787535/


All Articles