Sign in to follow this  
CoryG89

Automatically Dereferencing a Pointer

Recommended Posts

I am pretty sure I am right about this, but I was reading a chapter on pointers in my book, and I was just wanting to make sure. Say we start off by defining an array of integers like so:
int array[5] = {8, 3, 1, 9, 7};
and then a pointer:
int *ptr;
ptr = array;
I know that the name of an array, when used alone is a reference variable containing the array's starting address. What I am uncertain of would be the use of the pointer and the subscript operator. What would this result in.
ptr[3]
Is this automatically dereferenced, returning the value of subscript (9). Or does it return the address of array[3]. If it is automatically dereferenced are these two statements equivalent?
int number = ptr[3];           // Automatically dereferenced?
int number = *(ptr + 3)        // Adding to the address before dereferencing
Thanks in advance for the help.

Share this post


Link to post
Share on other sites
Quote:
Original post by CoryG89
If it is automatically dereferenced are these two statements equivalent?

int number = ptr[3]; // Automatically dereferenced?
int number = *(ptr + 3) // Adding to the address before dereferencing

Thanks in advance for the help.


For the purpose of this question, yes, they are the same.

Technically, there are some details dealing with fact that arrays are not pointers, but decay into them.

In C++, subscript operator is just an operator and can do anything, so if used with std::vector, or custom classes, the above might no longer hold, or even be possible.

Subscript operator can be applied to any pointer as well, so the following is valid syntax:
int * foo = ... // we don't know what
foo[77];
It might however not be valid or defined behavior.

Share this post


Link to post
Share on other sites
Quote:
Original post by CoryG89
If it is automatically dereferenced are these two statements equivalent?

int number = ptr[3]; // Automatically dereferenced?
int number = *(ptr + 3) // Adding to the address before dereferencing


a[i] is defined as *(a + i). So yes, they are equivalent.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this