user103214
user103214

Reputation: 3658

Do pointers have a 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]?

Upvotes: 3

Views: 438

Answers (7)

Arvind
Arvind

Reputation: 136

Pointers have always same size for particular type machine. Pointers have size of 4 bytes on 32 bit machine. It does not matter it is pointing to any data type or array of any data type. Pointer are variable which holds the address of any object.

For example:

int main()
{
    int x = 0;
    int * p = &x;

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

    cout<<sizeof(p)<<endl;
    cout<<sizeof(pt)<<endl;

    return 0;
}

You will get 4 for both the pointers.

Upvotes: 0

Belgi
Belgi

Reputation: 15082

Yes, a poiner usually have a size of int. you can check the size using the sizeof operator. For example:

int* p = NULL;
int size = sizeof(p);
printf("size is %d\n",size);

Upvotes: -1

Keith Thompson
Keith Thompson

Reputation: 263577

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.

Upvotes: 3

Septagram
Septagram

Reputation: 9795

During runtime there is no difference. During compilation time it is remembered, whether pointer in question is an array or not, as well as its size, and compiler guarantees that no inappropriate conversions will be made. If I'm not mistaken, inappropriate conversion in this case is conversion of common pointer to array pointer.

Also, as others have stated, during runtime pointer sizes are platform-dependent. On PC they have the same size as int: 4 bytes on 32-bit platforms, 8 bytes on 64-bit platforms.

Upvotes: 0

Oscar
Oscar

Reputation: 65

Your 'pointer with size' is an array of pointers

Upvotes: 0

Vaughn Cato
Vaughn Cato

Reputation: 64308

If you have

int *p = /* something */;
int (*q)[5] = /* something */;

Then *p is an int, but *q is an array of five ints, so (*q)[0] is an int.

Upvotes: 0

David Alber
David Alber

Reputation: 18111

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.

Upvotes: 5

Related Questions