Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do pointers have a size?

Tags:

c++

pointers

size

In C++, when using a pointer to multidimensional array like,

int arr[2][5];
int (*p)[5] = arr;

How does a int* is different from the one with size i.e. int (*)[5]?

like image 831
user103214 Avatar asked Apr 14 '26 16:04

user103214


2 Answers

Pointers are always the same size for any particular machine (virtual, or otherwise). On a 32-bit machine, pointers are 32-bits wide. On a 64-bit machine, they are 64-bits wide. Similar rules apply for more exotic (by today's standards) architectures.

like image 107
David Alber Avatar answered Apr 16 '26 07:04

David Alber


The difference is that they're of different types.

int* is a pointer to int; int (*)[5] is a pointer to an array of 5 ints. (The cdecl program is useful for interpreting declarations like these.)

It's very likely (but by no means guaranteed) that they'll both have the same size and representation. The difference, as between any two types, is in the operations that can be applied to objects of those types, and the meanings of those operations.

In response to the title, "Do pointers have a size?", certainly they do; the sizeof operator tells you what it is. But the 5 in int (*)[5] isn't the size of the pointer; it's the number of elements in the array to which the pointer points.

like image 36
Keith Thompson Avatar answered Apr 16 '26 07:04

Keith Thompson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!