【发布时间】:2018-01-21 03:11:26
【问题描述】:
我正在尝试填充包含在另一个结构中的结构中包含的数组的字段。
以下是结构定义:
struct Team
{
std::string name;
int position;
int **matches;
};
struct Championship
{
Team *teams;
unsigned int size;
};
然后,我在一个函数中分配内存。
Championship *createChampions(unsigned int n)
{
int i;
Championship *ptrcamp;
ptrcamp = new Championship;
ptrcamp -> size;
ptrcamp -> teams = new Team [n];
ptrcamp -> teams -> name;
ptrcamp -> teams -> position;
ptrcamp -> teams -> matches = new int *[2];
for (i = 0; i < 2; i++)
{
ptrcamp -> equipos -> partidos[i] = new int [n - 1];
}
return ptrcamp;
}`
当我尝试将每个团队的值保存在动态创建的“矩阵”中时,就会出现问题。
void fillcamp(Championship ptrcamp, int n)
{
int i, j, k;
string s;
for (i = 0; i<n; i++)
{
cin >> ptrcamp.teams[i].name;
cin >> ptrcamp.teams[i].position;
cout << ptrcamp.teams[i].name;
cout << ptrcamp.teams[i].position;
for (j = 0; j < 2; j++) // With this I pretend to fill each column.
{
for (k = 0; k < n - 1; k++)// In this step I tried to fill the matrix
{
ptrcamp.teams[i].*(*(matches + k) + j) = -1;
}
}
}
}
所以编译器说:
> Campeonato.cpp(52): error : identifier "matches" is undefined
1> ptrcamp.teams[i].*(*(matches + k) + j) = -1;
我尝试了所有方法,事实是不允许使用传统的 *var[n] 表示法。相反,我可以使用 *(var+n)。
感谢大家的帮助。
【问题讨论】:
-
请停止使用原始指针。请改用
std::vector和std::array(如果您真的需要指针,还可以使用智能指针) -
还有为什么不能用
matches[k][j]? -
你已经尝试了一切,除了正确的,
std::vector。 -
你需要一本像样的入门书。
-
@UnholySheep 我不知道。他们说 w 不能使用那个符号。
标签: c++ arrays pointers structure dynamic-memory-allocation