Array Pointer [C++]

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[5];      // array of 5 integers

int *ptr1;           // pointer to integer

int *ptr2;           // pointer to integer

ptr1 = &myArray[0];  // 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[5];                                 // 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[5];              // array of 5 integers.

int (*arrPtr)[5] = &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[5];                                // array of 5 integers.

int (*arrPtr)[5] = &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.

References:

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s