English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

why cant we create array of references in c++?
int a,b,c;
int &arr[3]={a,b,c};//error

is there any logcal explanation?

2007-06-04 00:44:50 · 5 answers · asked by Anonymous in Computers & Internet Programming & Design

5 answers

The 2nd line does not make any sense. It is like saying, "I want to allocate an array of 3 integers, and I want the address of the arr[] array. The 3 array elements contains the integer values of a, b, and c."
If you wish to create an array of pointers to a certain data type, you would do something like this:
int a,b,c;
int *arr[3]; // create an array of int pointers
// inside main:
arr[0]=&a; // arr[0] = address of integer 'a'
arr[1]=&b;
arr[2]=&c;

OR

int a,b,c;
int *arr[3]={&a, &b, &c};
The line above creates an array of pointers which points to an integer type. I use the {} braces to initialize the array to specify that the 3 pointers are the memory addresses of variables a, b, and c.

The & sign is used when you want to specify the address of a variable. You don't use it when you are allocating a variable.
Here's another example:
int a=5; // integer 'a' = 5
int b;
int *foo; // create a pointer to an integer
foo=&a; // foo = address of variable 'a'
b= *foo; // dereference foo. b=5

2007-06-04 03:57:02 · answer #1 · answered by Balk 6 · 0 0

The code above looks correct but you should know it is called and array of pointers in C and C++.

2007-06-04 01:26:33 · answer #2 · answered by Tempest 3 · 0 0

Because references are C++'s own terminology for 'pointers minus memory arithmetic' and within C/C++ arrays are really memory arithmetics so there is that conflict, arrays are pointers, so there is 'pointers of references?'

2007-06-04 01:50:56 · answer #3 · answered by Andy T 7 · 0 0

You seem to have the wrong mix of data types.
An & indicates the address of.
A * indicates a variable to store pointers.

Your statement should probably be
int *arr[3]={&a,&b,&c};

2007-06-04 01:02:42 · answer #4 · answered by AnalProgrammer 7 · 2 0

Because C and its descendants are nasty, unfriendly languages.

Try Python instead.

2007-06-04 00:59:56 · answer #5 · answered by poorcocoboiboi 6 · 0 1

fedest.com, questions and answers