Jump to content
  • Advertisement
Sign in to follow this  
CoryG89

Automatically Dereferencing a Pointer

This topic is 3045 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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 is defined as *(a + i). So yes, they are equivalent.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!