I am trying to use vector of structs for my need, and was writing some sample test code to understand the behavior. Below is the test code I have written:
test.h
struct Student {
char *name;
int id;
char *section;
};
typedef struct Student student_t;
test.cc
#include <iostream>
#include <vector>
#include "test.h"
using namespace std;
int main() {
vector<student_t> vst;
//vst.resize(2);
student_t st;
st.name = "student1";
st.id = 4503;
st.section = "secA";
vst.push_back(st);
vst.push_back({"student2", 4504, "secA"});
for(auto const& s:vst) {
std::cout<< " student: " << std::endl;
std::cout << "Name : " << s.name <<
std::cout << " Id : " << s.id <<
std::cout << " Section : " << s.section << std::endl;
}
return 0;
}
Output without specifying the size of the vector:
student:
Name : student10x6040c8 Id : 45030x6040c8 Section : secA
student:
Name : student20x6040c8 Id : 45040x6040c8 Section : secA
When resize(2) is used:
student:
Name :
I can't figure out the issue! Is there a problem with my initialization?