简体   繁体   English

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

[英]How to use int array in typedef struct (C)

can you please explain how to use int array in typedef struct? 您能解释一下如何在typedef结构中使用int数组吗?

In my header i have code: 在我的标头中,我有代码:

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

In some function (where i include my header file) i use: 在某些功能(其中包括头文件)中,我使用:

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

Thank you for your reply. 谢谢您的回复。

If you want to do it dynamically 如果您想动态地做

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)

If you do not want to use dynamic memory 如果您不想使用动态内存

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)

EDIT 编辑

As suggested by alk in the comments, 正如alk在评论中所建议的,

Test* tmp = malloc(sizeof *tmp);

is better then 那就好了

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

Since, to quote alk "The former would survive a change in the type definition of tmp without any further code changes" 因为,引用alk “前者将在tmp类型定义的更改中幸免,而无需任何进一步的代码更改”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM