I am playing around with pointer to array. Saw this tutorial's code as below.
I understand that sizeof(int) returns the number of bytes used to store an int, while sizeof(int*) returns the number of bytes used to store a pointer. But why is it sizeof(*ptr) = 20? Why is it bigger than the ptr's size?
1 2 3 4 5 6 7 8 9 10
int main()
{
int arr[] = { 3, 5, 6, 7, 9 };
int *p = arr;
int (*ptr)[5] = &arr;
printf("sizeof(p) = %lu, sizeof(*p) = %lu\n", sizeof(p), sizeof(*p));
printf("sizeof(ptr) = %lu, sizeof(*ptr) = %lu\n", sizeof(ptr), sizeof(*ptr));
return 0;
}
If we have some object type T, and we have a pointer T* ptr which points to an object of type T, sizeof(ptr) would give us the size of the pointer and sizeof(*ptr) would give us the size of the object ie. sizeof(T).
If the object type T is an array, then sizeof(*ptr) would give us the size of the array.
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
int main()
{
using T = int[5] ; // type T is 'array of 5 int'
std::cout << sizeof(T) << '\n' ; // size of 'array of 5 int'
T* ptr = nullptr ; // type T* is 'pointer to array of 5 int'
std::cout << sizeof(ptr) << '\n' ; // size of 'pointer to array of 5 int'
std::cout << sizeof(*ptr) << '\n' ; // size of 'array of 5 int'
}
No, sizeof(int) and sizeof(T *) are independent. In portable code it's an error to assume that they're always the same.
Just FWI, if it's available, sizeof(uintptr_t) == sizeof(T *). uintptr_t is an integer type provided for temporary storage of pointers.
Remember that sizeof is evaluated at compile time and the result is a constant that's hard-coded into the final executable, while normal expressions are evaluated at run time. Therefore,
1 2 3 4
T x = /*whatever*/;
size_t n = sizeof(x);
x = /*whatever else*/;
size_t m = sizeof(x);
at the end of this snippet, regardless of what you do in the commented sections, n == m.