|
const reference to integer array |
William Labbett
Member #4,486
March 2004
|
Hi, new to C++. Trying to pass a const reference to an array of 4 integers. What I've tried doesn't work :- void Process_Input(const int []& key_states ); void Process_Input(const int key_states[]& ); At least I think that's what the compiler error is about.
|
torhu
Member #2,727
September 2002
|
void Process_Input(const int& key_states[] ); |
William Labbett
Member #4,486
March 2004
|
According to the compiler that's an array of references. I need a reference to an array.
|
SiegeLord
Member #7,827
October 2006
|
I'm guessing you can't do that: typedef int int_arr[]; void foo(int_arr& arr) { }
test.cpp:3:22: error: parameter ‘arr’ includes reference to array of unknown bound ‘int []’ Don't use C arrays in function arguments, ever. They are just a mess, and are the most broken aspect of C. "For in much wisdom is much grief: and he that increases knowledge increases sorrow."-Ecclesiastes 1:18 |
torhu
Member #2,727
September 2002
|
Google says this works, but I don't know: But why are you using a reference? Arrays are already passed as pointers. |
Oscar Giner
Member #2,207
April 2002
|
A reference to an array just doesn't make sense. What are you trying to achieve? My guess is that you want a reference to a pointer: void Process_Input(int* &key_states); You cannot pass a static array to that, though (since the address of an array cannot be modified, the reason why a reference to an array doesn't make sense). [edit] -- |
Kitty Cat
Member #2,815
October 2002
|
void foo(const int key_states[]) Effectively, a reference isn't much more than a const pointer that auto-dereferences when you access it. Subscripting (eg, key_states[i]) dereferences a pointer automatically, and because of an array's tendency to automatically supply a reference when not subscripted, a reference to a const integer array would be provided like this: -- |
Arthur Kalliokoski
Second in Command
February 2005
|
Kitty Cat said: void foo(const int key_states[]) It's not a pointer because it can't be altered, just like a reference. You could do pointer stuff to access the elements, but the memory offset of key_states[0] can't be altered in any meaningful C program. They all watch too much MSNBC... they get ideas. |
anonymous
Member #8025
November 2006
|
You can't have a reference to an array, only to an array of particular size. Each array type has fixed size. The main practical use is probably: template <class T, unsigned N> unsigned length(const T (&)[N]) { return N; }
|
|