你能解释一下如何在 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/