Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference to array of struct

I am learning about references in C++. Is it not possible to create a reference to an array of structs?

struct student {
    char name[20];
    char address[50];
    char id_no[10];
};

int main() {
    student test;
    student addressbook[100];
    student &test = addressbook; //This does not work
}

I get the following errors:

a reference of type "student &" (not const-qualified) cannot be initialized with a value of type "student [100]"
Error C2440 'initializing': cannot convert from 'student [100]' to 'student &'

like image 551
zer0c00l Avatar asked Mar 03 '26 07:03

zer0c00l


1 Answers

The type of the reference must match what it is referring to . A reference to a single student cannot refer to an array of 100 students. Your options include:

// Refer to single student
student &test = addressbook[0];

// Refer to all students
student (&all)[100] = addressbook;
auto &all = addressbook;               // equivalent
like image 197
M.M Avatar answered Mar 05 '26 19:03

M.M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!