How to Create reference to an array in C++
Hi Guys,
I have studied that we cannot create references to arrays in C++. But when i was reading a book by Stroustrup, he has asked in the exersice to create a reference to an array of 10 elements. Can anybody demonstrate the same??
PS: I believe i would have to create individual references to each of the element in the array..... am i right!!!!
Re: How to Create reference to an array in C++
Quote:
Originally posted by shiv_tech_quest
Hi Guys,
I have studied that we cannot create references to arrays in C++. But when i was reading a book by Stroustrup, he has asked in the exersice to create a reference to an array of 10 elements. Can anybody demonstrate the same??
PS: I believe i would have to create individual references to each of the element in the array..... am i right!!!!
Whoever told you that you can't didn't know what they were talking about.
You make a reference to an array like this
Elementtype (&ReferenceName)[NumElDim0][NumElDim1][NumElDim2]; // etc. for as many dimensions as you want
For instance, if you wanted a reference to a 2 dimensional int array of dimension lengths 3 and 5 you'd do this
int Array[3][5]; // This is the actual array
int (&ArrayRef)[3][5] = Array; // Here's our reference
If your instructor told you you can't make a reference to an array but you can make a poitner to an array then he most likely didn't teach you how to make a pointer to an array -- he probably told you how to make a pointer to the first element of an array (which is very different).
A pointer to an array is done the same way as you'd do a reference to an array.
int Array[3][5]; // This is the actual array
int (*ArrayPtr)[3][5] = &Array; // Here's our pointer
Just remember that if you use a pointer to an array (as opposed to a reference) you will have to explicitly dereference it before you use it.
Thanks a ton Polymorphic OOP
I am enlightened by your answer.......
Have a wonderful day... and keep smiling...... you look terrific that way :)
regards,
shiv