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

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

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

结构定义如下:

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;
}`

当我尝试在动态创建的 "matrix" 中保存每个团队的值时出现问题。

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;

如果我是你,我会简化该行(并为变量提供清晰的名称),以便在取消引用之前更清楚你真正指向的内容。仅此一项就可以解决您的问题。