Reputation: 3
Currently I am making dynamic allocation of structs within structs in C++. So, I made a code that can be dynamically allocated that I think. Here is the code that I made it :
#include<iostream>
using namespace std;
int cnt = 0;
struct num{
int x;
int y;
};
struct name {
char Stu[30] = { 0 };
num *number;
};
int input(int& a) {
if (cnt == 0) {
cout << "입력할 수 : ";
cin >> a;
cnt++;
return a;
}
if (cnt == 1) {
cout << "입력할 수 : ";
cin >> a;
cnt++;
}
}
void input(char *pt) {
if (cnt == 2) {
cout << "입력할 글자 : ";
cin >> pt;
cnt++;
}
}
int inputnum(int i) {
cout << "할당할 숫자를 쓰시오 : ";
cin >> i;
return i;
}
void printdata(name *pSt, int i, int j) {
cout << pSt[i].number[j].x << endl;
cout << pSt[i].number[j].y << endl;
cout << pSt[i].Stu << endl;
}
int main() {
int num1 = 0;
int num2 = 0;
num1 = inputnum(num1);
num2 = inputnum(num2);
name* student = new name[num1];
for (int i = 0; i < num1; i++) {
for (int j = 0; j < num2; j++) {
student[i].number = new num[num2];
input(student[i].number[j].x);
input(student[i].number[j].y);
input(student[i].Stu);
cnt = 0;
}
}
for (int i = 0; i < num1; i++) {
for (int j = 0; j < num2; j++) {
printdata(student, i, j);
}
}
}
But if I input more than 2 in num2, output number is weird like -842150451. How can I do dynamic assignment to a struct inside a struct in C++?
Upvotes: 0
Views: 40
Reputation: 16328
There are several issues with your code.
First, use std::string
instead of char[30]
. Second, don't allocate memory unless is necessarily. There is no need for num* number
. Use a std::vector
.
You can put your code as follows:
struct num {
int x;
int y;
};
struct name {
std::string Stu;
std::vector<num> number;
};
-842150451
is not a weird number. It's decimal for 0xCDCDCDCD. This is a value used by Microsoft debug CRT to represent uninitialized heap memory. See here.
Concerning the input
functions, why don't you write some simpler functions?
void input_x(int& x)
{
cout << "입력할 수 : ";
cin >> x;
}
void input_y(int& y)
{
cout << "입력할 수 : ";
cin >> y;
}
void input_s(char *pt)
{
cout << "입력할 글자 : ";
cin >> pt;
}
Which you can use as follows:
for (int i = 0; i < num1; i++) {
for (int j = 0; j < num2; j++) {
student[i].number = new num[num2];
input_x(student[i].number[j].x);
input_y(student[i].number[j].y);
input_s(student[i].Stu);
}
}
The input_s
should use std::string
, though, if you use what I suggest above:
void input_s(std::string& pt)
{
cout << "입력할 글자 : ";
cin >> pt;
}
As for name* student
you can replace that with std::vector<name>
:
std::vector<name> student;
for (int i = 0; i < num1; i++) {
for (int j = 0; j < num2; j++) {
name s;
s.number.resize(num2);
input(s.number[j].x);
input(s.number[j].y);
input(s.Stu);
student.push_back(s);
}
}
Upvotes: 1