【问题标题】:How to set a value in a multi-dimensional struct array using a struct pointer?如何使用结构指针在多维结构数组中设置值?
【发布时间】:2021-11-26 07:12:24
【问题描述】:

我有一个结构:

typedef struct{
int age;
int height
}Human;

我用该结构创建了一个多维数组:

Human human_table[3][2]={ 
{{1,1},{1,1}},
{{1,1},{1,1}},
{{1,1},{1,1}},
};

我创建了一个指向表的指针

typedef struct human_table *humanPointer;

现在的问题是,如何创建一个函数来修改上面的表格?

我目前有这个:

void Modify_Human_age(humanPointer human_table, int x, int y, int New_Age)
{
human_table[x][y]->age=New_Age;
}

但我收到一个错误,正在寻求有关如何修复 Modify_Human_age 函数的帮助。

谢谢

【问题讨论】:

  • 你的错误是什么?
  • 无效使用未定义类型“struct human_table”并取消引用指向不完整类型“struct human_table”的指针
  • struct human_table 是一个类型的名称。你永远不会定义这种类型。您定义了一个名为human_table 的变量,但它与struct human_table 无关。将所有提及的struct human_table 替换为Human
  • 您也错误地使用了您的可能指向表的指针。您最好使用指向 单行 的指针。

标签: arrays c pointers struct


【解决方案1】:
  1. 永远不要在 typedef 后面隐藏指针。它使代码更难维护和阅读。所以从你的代码中删除typedef

  2. C 中的多维表在表的事实表中。所以二维表是一个行表。所以 id X 是行大小,Y 是行数,数组的定义应该是 type arr[Y][X]

  3. 对于索引和大小,请使用正确的 (size_t) 类型而不是 int

void Modify_Human_age(size_t x, size_t y, Human (*human_table)[x],  int New_Age)
{
    human_table[y][x].age=New_Age;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-02
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多