This post is for you if you know about arrays and pointers in C/C++ [check references for more info]
At first, we have to know the difference between:
- Pointer to array.
- Pointer to first element in array.
1. Pointer to first element in array.
It’s common to hear that “Array name is a pointer to that array“, but it is not correct, Array name yields a memory location, so it can be treated as a pointer, and the question is “Pointer to what?”
– It’s a pointer to the first element in that array, not pointer to the array itself.
Look at this:
int myArray; // array of 5 integers int *ptr1; // pointer to integer int *ptr2; // pointer to integer ptr1 = &myArray; // ptr1 now is a pointer to the first element in "myArray" ptr2 = myArray; // ptr2 is also a pointer to the first element [prt1 equal ptr2]
And by using this way, you don’t have a pointer to the whole array, and that’s why you can’t get the length of array by using sizeof operator, and also can’t reallocate the array.
int myArray; // array of 5 integers int arraySize1 = sizeof(myArray) / sizeof(int); // arraySize1 will be equal 5 *ptr = myArray; // pointer to first element int arraySize2 = sizeof(ptr) / sizeof(int); // arraySize2 will be equal 1
arraySize2 = 1 and that seems logical, as the size of a pointer to integer = 4 bytes. -Based on machine and OS-
2. Pointer to Array
This is how the pointer to array looks like:
int myArray; // array of 5 integers. int (*arrPtr) = &myArray; // Pointer to the whole array.
And read as “arrPtr is pointer to array of 5 integers”
and now you can get the size of the array with using sizeof operator:
int myArray; // array of 5 integers. int (*arrPtr) = &myArray; // pointer to array int arraySize = sizeof(*arrPtr) / sizeof(int); // arraySize will be equal 5
You may need to read this [Reading C type declarations] if you this confusing.