I am trying to understand the concept of dynamic memory allocation. I have written some code that dynamically allocates an array of structs. The struct name is data and contains name and roll number. It asks user how many times you want to enter. After entering data it is supposed to search the data according to roll number. It crashes when searching for a particular roll number. Below is the code.
struct data
{
char name[50];
int roll; float cgpa; char camp[3];
};
int main()
{
data *p;
int i;
cout << "how many times you want to enter data? "; cin >> i;
p = new data[i];
for (int k = 0; k < i; k++)
{
cout << "Enter your name:";
cin >> p[k].name;
cout << "Enter your roll number:";
cin >> p[k].roll;
cout << endl<<endl;
p++;
}
int r;
cout << "enter roll number to search for :"; cin >> r;
for (int j = 0; i < i; j++){
if (p[j].roll == r)
{
cout << "Roll number:" << p[j].roll << endl; cout << "Name:" << p[j].name << endl;
}
else{
cout << "Not found!" << endl;
break;
}
}
delete []p;
return 0;
}