Jump to content
  • Advertisement
Sign in to follow this  
Mantear

Reference to an array element

This topic is 4885 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

Greetings, I was wondering if it was possible to directly get the reference to an element in an array. I don't seem to be able to. Example:
int array[3];
int** myPtr;

myPtr = &array; // '*myPtr' is equivalent to 'array'

myPtr = (&array) + 1;  // doesn't work, '*myPtr' points past the array

myPtr = &(array + 1); // compiler error
I'm playing around with pointers to pointers, and would like to know how I can get the reference to an element in array, such as 'array[1]', if it's even possible. Thanks!

Share this post


Link to post
Share on other sites
Advertisement
Assuming C++, you seem to be declaring your types wrong. A reference is declared with &.

int array[3];

int & element = array[1]; // reference to the second element

If you mean you want to get a pointer to an element in an array:

int * element_ptr = array + 1; // pointer to the second element

Share this post


Link to post
Share on other sites
I want to have it so '*myPtr' points to 'array[1]' (so that myPtr is a pointer to a pointer to the element located at array[1]). Is this even possible?

Share this post


Link to post
Share on other sites
The issue with that is it won't survive once element_ptr goes out of scope. Assume that 'array' and 'myPtr' are class members, and so won't go out of scope.

Share this post


Link to post
Share on other sites
Well, if you want a pointer to a pointer, then it won't "survive" if the pointer you're pointing at goes out of scope, no matter how you do it.

The first thing I would check is to be really sure you want a double-pointer. They're rarely needed in C++, especially with the use of references and of the tools provided in the standard library.

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.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!