【问题标题】:How to use int array in typedef struct (C)如何在 typedef struct (C) 中使用 int 数组
【发布时间】:2015-11-03 20:08:04
【问题描述】:

你能解释一下如何在 typedef struct 中使用 int 数组吗?

在我的标题中我有代码:

typedef struct {
    int arr[20];
    int id;
} Test;

在某些函数中(我包含我的头文件)我使用:

Test tmp = malloc(sizeof(Test));
tmp.id = 1;
//and how to use array arr?
//for example I want add to array -1

感谢您的回复。

【问题讨论】:

  • tmp.arr[0] = -1?您必须跟踪最后一个索引,因为您无法将内容“添加”到数组中。它们的大小是固定的(除非你使用realloc
  • 执行此命令后出现分段错误(核心转储)错误。
  • 显示的代码不会编译。

标签: c arrays struct


【解决方案1】:

如果你想动态地做到这一点

Test* tmp = malloc(sizeof(Test));
tmp->id = 1;        //or (*tmp).id = 1;
tmp->arr[0] = 5;    // or (*tmp).arr[0] = 5
                    // any index from 0 to 19, any value instead of 5 (that int can hold)

如果你不想使用动态内存

Test tmp;
tmp.id = 1;      //any value instead of 1 (that int can hold)
tmp.arr[0] = 1;  //any value instead of 1 (that int can hold)

编辑

根据 cmets 中 alk 的建议,

Test* tmp = malloc(sizeof *tmp);

更好

Test* tmp = malloc(sizeof(Test));

因为引用alk “前者将在tmp 的类型定义发生变化后继续存在,无需任何进一步的代码更改”

【讨论】:

  • (*tmp). 很少见,而使用tmp-> 则不然。
  • Als 使用Test * tmp = malloc(sizeof *tmp); 而不是... malloc(sizeof(Test)); 不仅更好,而且更节省。
  • @alk 它们有什么不同?
  • 前者可以在tmp 的类型定义更改后继续存在而无需任何进一步的代码更改,这就是为什么提到“saver”。
  • @alk,没关系,我编辑了答案。但是由于两者都在同一条线上,因此很容易更改两者。前一个看起来不太可读。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-14
  • 1970-01-01
  • 2021-03-22
  • 2011-05-04
相关资源
最近更新 更多