指向结构中的数组的指针,其中每个字段都是一个动态数组

Pointer pointing to array in a structure with each field as an dinamic array

本文关键字:数组 动态 一个 结构 指针 字段      更新时间:2023-10-16

我正在尝试填充包含在另一个结构中的结构中包含的数组的字段。

以下是结构定义:

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(。

谢谢你们的帮助。

"matches" 是一个字段,而不是变量本身。 您需要用点或箭头表示法作为前缀。 在你的代码中,看起来好像你认为你正在这样做,但事实并非如此;我和编译器看着那行代码一样困惑。

你的意思是:

*(*( ptrcamp.teams[i].matches + k) + j) = -1;

如果我是你,我会简化那行(并给变量明确名称(,以便在取消引用之前更清楚地表明你真正指向的内容。 仅此一项就可能解决您的问题。