c - 如何在 typedef struct 中使用 int 数组 (C)

标签 c arrays struct

你能解释一下如何在 typedef 结构中使用 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

感谢您的回复。

最佳答案

如果你想动态地做

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)

编辑

根据 alk 的建议在评论中,

Test* tmp = malloc(sizeof *tmp);

那就更好了

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

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

关于c - 如何在 typedef struct 中使用 int 数组 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33497133/

相关文章:

arrays - 使用线段树从给定数组中找到最大和子数组

c - 如何在 C 中创建动态结构数组

c - OpenCv Makefile Undefined symbols for architecture x86_64 错误

c - 输出窗口卡在黑屏上

c++ - 我如何使用 libavfilter 在我的视频播放器软件中去隔行帧

javascript - 在 div 中显示 javascript 数组

c - 字符串数组插入问题

c - 具有灵活阵列成员的不透明结构

c - 为本地声明公开一个 typedef 结构,但将结构成员访问权限保留在定义它的模块中

c - 如何在不使用互斥量的情况下在多个线程之间进行同步,以便它们的事务 ID 是唯一的?