【问题标题】:Pointer pointing to array in a structure with each field as an dinamic array指向结构中数组的指针,每个字段都为动态数组
【发布时间】: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::vectorstd::array(如果您真的需要指针,还可以使用智能指针)
  • 还有为什么不能用matches[k][j]
  • 你已经尝试了一切,除了正确的,std::vector
  • 你需要一本像样的入门书。
  • @UnholySheep 我不知道。他们说 w 不能使用那个符号。

标签: c++ arrays pointers structure dynamic-memory-allocation


【解决方案1】:

“matches”是一个字段,而不是一个变量。您需要在它前面加上点或箭头符号。在您的代码中,您似乎认为自己正在这样做,但事实并非如此;我和编译器看到那行代码一样困惑。

你的意思是:

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

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

【讨论】:

  • 所以,据我所知,点不能应用于指针。在我的代码中,为什么这样有效?我应该使用箭头运算符,如何?我很困惑,这对我来说是一个新概念。
  • 这里的点不在指针上。成员“teams”作为数组被访问。 ptrcamp.teams[i] 是该数组中的第 i 个元素,类型为 Team
猜你喜欢
  • 2011-01-02
  • 1970-01-01
  • 1970-01-01
  • 2012-07-16
  • 1970-01-01
  • 2017-06-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多