Reputation: 65
I'm trying to use an object name from the array. I know I wrote wrong code below inside the loop. How should I write code on the below pointer lines for using object name from the array?
Here's the full code:
#include <iostream>
using namespace std;
class Students{
public:
int index;
string name;
string father;
};
int main() {
string nname[] = {"John", "Doe"};
string fname[] = {"Ex John Father", "Ex Doe Father"};
int NarrSize = sizeof(nname)/sizeof(nname[0]); // Size of nname array
int FarrSize = sizeof(fname)/sizeof(fname[0]); // Size of fname array
if( NarrSize == FarrSize ){ // Check if both array size is same
for(int i=0; i<NarrSize; i++){
Students nname[i];
nname[i].index = i+1;
nname[i].name = nname[i];
nname[i].father = fname[i];
}
}
return 0;
}
Upvotes: 0
Views: 577
Reputation: 75062
You should allocate the array before the loop.
Also the name nname
is already used as the array of string
, so you should give another name to your array of Students
.
Using non-standard VLA (variable-length array):
if( NarrSize == FarrSize ){ // Check if both array size is same
Students student_array[NarrSize]; // allocate array
for(int i=0; i<NarrSize; i++){
student_array[i].index = i+1;
student_array[i].name = nname[i];
student_array[i].father = fname[i];
}
}
Using std::vector
instead:
if( NarrSize == FarrSize ){ // Check if both array size is same
std::vector<Students> student_array(NarrSize); // allocate vector
for(int i=0; i<NarrSize; i++){
student_array[i].index = i+1;
student_array[i].name = nname[i];
student_array[i].father = fname[i];
}
}
Add #include <vector>
to use std::vector
.
Upvotes: 4