简体   繁体   中英

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 ie int (*)[5] ?

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.

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.

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.

你的'指针大小'是一个指针数组

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.

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM