【问题标题】:How to obtain value from an array of struct? (C) [closed]如何从结构数组中获取值? (C) [关闭]
【发布时间】:2020-10-05 01:30:22
【问题描述】:

我一直在尝试访问我在结构数组中声明的值,如下所示。

struct info{
    int name[];
    int age[];
};

const struct info arr_info[] = {{Pat,15}, {Emily,4}, {Matt,22}};

我用的是下面的方法,但是发现只获取到了指针。这是一个问题,因为我试图将此值传递给函数。

arr_info[2].age

在我的代码中需要什么才能访问值本身?

提前致谢。

【问题讨论】:

  • int x[] 并不代表你认为的那样。这是一个由内而外的结构。摆脱定义中的那些[]
  • 什么是Pat?你的意思是"Pat"
  • 编辑问题以提供minimal reproducible example

标签: arrays c pointers struct


【解决方案1】:

你的意思可能是这样的:

// Define struct called "info"...
struct info {
    // ...with a character string property "name"...
    char* name;
    // ...and a single integer representing "age".
    int age;
};

const struct info arr_info[] = {{"Pat",15}, {"Emily",4}, {"Matt",22}};

您定义的是一个结构数组其中包含数组,考虑到分配行的意图,这实际上没有任何意义。这意味着每个 info 结构可以有 多个名称多个年龄 当您想要的是多个 info 结构时,每个结构都有 一个 名称和一个年龄。

【讨论】:

  • 谢谢。我忘了在我的帖子中提到我的名字实际上在程序的早期被声明为整数。
  • 如果您想使用int 而不是char*,这很容易解决。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-09
  • 1970-01-01
  • 1970-01-01
  • 2020-08-04
  • 1970-01-01
  • 1970-01-01
  • 2021-04-03
相关资源
最近更新 更多