[英]Not sure how to use these unnamed structs that were given as prototypes. C
EDIT: These structure definitions were given to me and cannot be altered in any way. 编辑:这些结构定义是给我的,不能以任何方式更改。
Let's say in struct DB
I would like to access the name of 3rd element in db. 假设在
struct DB
我想访问db中第3个元素的名称。 How would I go about that? 我将如何处理? I would think I would be able to do this:
我认为我可以做到这一点:
DB->db[2].name;
but that doesn't work. 但这不起作用。
Also, how would I define one of these structs as a parameter inside a function? 另外,我如何将这些结构之一定义为函数内的参数?
typedef struct {
char name[MAX_NAME + 1];
unsigned long pass;
} DBEntry;
typedef struct {
DBEntry db[MAX_ENTRIES];
int size;
} DB;
First you have to create object for struct DB
. 首先,您必须为struct
DB
创建对象。 Then you can access it's members. 然后,您可以访问它的成员。
DB obj;
strcpy(obj.db[2].name, "abc");
These are types , not variables . 这些是类型 ,而不是变量 。
To use them: 要使用它们:
DB db;
db.size = 1;
strcpy(db.db[0].name, "name");
db.db[0].pass = 0xdeadbeef;
...
First of all, there is no struct DB
; 首先,没有
struct DB
; there is a type name DB
which identifies an untagged structure type, but that's separate from struct DB
. 有一个类型名称
DB
可以标识未标记的结构类型,但这与struct DB
是分开的。
How you access the elements depends on the variable declaration: 如何访问元素取决于变量声明:
DB db1 = ...;
DB *db2 = ...;
With variable db1
, you access the name of the 3rd element using: 使用变量
db1
,您可以使用以下命令访问第三个元素的名称:
printf("%s\n", db1.db[2].name);
With variable db2
, you access the name of the 3rd element using: 使用变量
db2
,您可以使用以下命令访问第三个元素的名称:
printf("%s\n", db2->db[2].name);
You can define a function that takes these types using: 您可以使用以下方法定义采用这些类型的函数:
void magic_function(DB db1, DB *db2, DBEntry de1, DBEntry *de2)
{
printf("%s\n", db1.db[0].name);
printf("%s\n", db2->db[0].name);
printf("%s\n", de1.name);
printf("%s\n", de2->name);
}
You can declare it in a header using: 您可以使用以下命令在标头中声明:
extern void magic_function(DB db1, DB *db2, DBEntry de1, DBEntry *de2);
Personally, I prefer the extern
there for symmetry with the extern
declarations for those rare global variables that are declared in the same header, but it is not actually necessary ( extern
is assumed if it is omitted). 就我个人而言,我更喜欢使用
extern
来与那些在同一标头中声明的罕见全局变量的extern
声明保持对称,但是实际上并没有必要(如果省略extern
则假定为extern
)。 If the function is only referenced from a single source file, it should be static
, of course (and not declared in any header). 如果仅从单个源文件引用该函数,则该函数当然应该是
static
的(并且不在任何标头中声明)。
First you have to declare as object like this .. 首先,您必须像这样声明对象。
DB db1;
db1.db[0].pass = 35;
I think , In your code , you have try to store number of names and access to those elements. 我认为,在您的代码中,您尝试存储一些名称并访问这些元素。 If you try that, your
DBEntry
structure should be 如果您尝试这样做,则您的
DBEntry
结构应为
typedef struct {
char *name[MAX_NAME + 1];
unsigned long pass;
} DBEntry;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.