【问题标题】:How to access a specific structure in array in C?如何访问C中数组中的特定结构?
【发布时间】:2017-01-16 18:14:24
【问题描述】:

我有这个:

typedef struct{
    field_1;
    field 2;
    .....
}student;

typedef struct{
    student record[100];
    int counter;
}List;

然后我想添加每个“学生”的信息,例如:

List *p;
gets(p->list[index]->field_1);

但是当我编译代码时它抛出了这个:

[Error] base operand of '->' has non-pointer type 'student'

那么为什么我不能指向“列表”以及访问“列表”中特定“记录”的方式?

【问题讨论】:

  • 使用. 运算符代替->(第二个)..
  • 或者complentarty创建一个指向student的指针数组。

标签: c arrays structure


【解决方案1】:

添加代码 sn-p 可以帮助您将值读/写到记录中。 完成后释放指向结构的指针。

typedef struct{
int age;
int marks;
}student;

typedef struct{
student record[100];
int counter;
}List;

int main()
{ 
    List *p = (List*)malloc(sizeof(List));

    p->record[0].age = 15;
    p->record[0].marks = 50;
    p->counter = 1;
    free(p);
    return 0;
}

【讨论】:

  • 不错。我在询问使用 malloc() 函数。但是调用sizeof(List) 会创建未使用的counter 变量吗?
  • 不,不会。它只会为计数器变量分配 4 个字节的内存。
【解决方案2】:

列表本身p 是一个指针,但值record[100] 不是。您将使用-> 运算符来访问来自p 的值,然后使用. 运算符来访问来自成员records 的值。

【讨论】:

  • 那我可以使用 malloc() 函数而不是给出固定数量的记录吗?会不会有什么问题?
【解决方案3】:

当你写作时

  `p->record[index]->field_1`

它被扩展为 (*p).(*record[index]).field_1

  record[index]` 

本身返回一个值,因此在此之前添加 * 运算符是没有意义的。但是你可以使用

p->(record+index)->field_1

【讨论】:

    猜你喜欢
    • 2021-02-11
    • 2018-06-08
    • 2017-01-28
    • 2018-04-11
    • 1970-01-01
    • 1970-01-01
    • 2014-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多