I just bought "The C++ programming language" By Stroustrup and one of the exercises in it says to reference an array of 10 integers. Well here is the code I have but it doesn't work
1 2 3 4 5 6 7 8 9 10 11 12 13
//reference to an array of 10 integers
cout << endl << endl << "Values in nArray2 when referenced" << endl;
int nArray2[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int& pnArray2 = nArray2[10];
for(;pnArray2 < 10; pnArray2++)
{
cout << pnArray2 << endl;
}
The code compiles but the count starts ouputing at -2 and it doesn't output the referenced array.
I'm not very good with refrences, but is int& pnArray2 = nArray2[10]; correct? It seems like it would just get the refrence of the value at 10 and probably screw up the rest of your code.
firedraco is right. References can't be incremented. Only the value the reference.
In any case, initializing it to nArray2[10] doesn't make much sense. You'd have to initialize it to nArray2, but then it'd be easier to just use the pointer directly.
EDIT: Oh, yeah. And there are better books out there for learning C++ than The C++ Programming Language.
I didn't know you couldn't reference an entire array. I will try that reference to pointer method.
@helios Other books I've read teach the language in a bad order and are not indepth enough.
template< typename T, size_t N >
size_t ArraySize( T (& const)[ N ] )
{
return N;
}
Edit: some older compilers (namely some versions of GCC) have issues with the parameter to this function and/or fail to match the const properly so sometimes you also have to declare the non-const version too:
1 2 3 4 5
template< typename T, size_t N >
size_t ArraySize( T (&)[ N ] )
{
return N;
}
The reason for using the template method is that it is hard(er) to get wrong. As opposed to the sizeof(array)/sizeof(array[0]) implementation which my original post clearly demonstrated is easily possible to get wrong :)
Okay thank you for the help. I was just wondering if it could be done and how to do it. Maybe I Stroustrup worded the question wrong and he meant pointer. I know how to access arrays through pointers.