[英]how to access struct member inside an array of structs in C
I have an array of structs which I use to get a certain member, problem I have is that I would only like to access a particular member of a struct, not the whole struct itself. 我有一个用来获取某个成员的结构体数组,我遇到的问题是我只想访问结构体的特定成员,而不是整个结构体本身。 So eg if my struct is declared like this: 因此,例如,如果我的结构像这样声明:
static _Plyr {
char* firstName;
int age;
char* lastName;
}
typedef struct _Plyr Player;
and I have a table of them...e..g 我有一张桌子...例如
static Player Table[NUM] = {
{"John", 24, "Wall"},
{"Carmelo", 33, "Anthony"},
....
}
I'd like to have a function that returns eg a person's last name based of their first name. 我想要一个函数,该函数可以根据一个人的名字返回一个人的姓氏。 So I have a *char function and I know how to get the whole struct back but I only want to get a certain member from a particular struct in this case, their last name...so I need to fix my return statement 所以我有一个* char函数,我知道如何取回整个结构,但是在这种情况下,我只想从特定结构中获取某个成员,即他们的姓氏...所以我需要修正我的return语句
Part of my code 我的代码的一部分
char* getLastName(char* string){
char* first;
for (int i = 0; i < REGCOUNT; i++){
first = Table[i].firstName;
if (strcmp(first, str) == 0){
return &Table[i].lastName;
}
}
}
I've tried Table[i].lastName, Table[i]->lastName,
...and neither seems to work. 我已经尝试过Table[i].lastName, Table[i]->lastName,
...似乎都无法正常工作。 I know &Table[i]
gives me the adress of the struct itself and then I can access it from there but I'd simply like to get the members themselves and not the whole struct. 我知道&Table[i]
为我提供了结构本身的地址,然后可以从那里访问它,但是我只是想获取成员本身而不是整个结构。 Thank you for your time 感谢您的时间
Check the below code, 检查以下代码,
typedef struct _Plyr {
char* firstName;
int age;
char* lastName;
} Player; /* typedef structure _Plyr into Player*/
static Player Table[] = { /* Table with NUM of items*/
{"John", 24, "Wall"},
{"Carmelo", 33, "Anthony"},
---------------------------
---------------------------
};
#define NUM (sizeof(Table)/sizeof(Player)) /* Maximum number of items in table */
char* getLastName(char* string){
char* first;
for (int i = 0; i < NUM; i++){
first = Table[i].firstName;
if (strcmp(first, string) == 0){
return Table[i].lastName;
}
}
}
Check the comments added in code. 检查代码中添加的注释。
&Table[i].lastName
is not a char*
, you have to return Table[i].lastName
to return address of lastName
. &Table[i].lastName
不是char*
,您必须返回Table[i].lastName
才能返回lastName
地址。
you must use RegTable[i].lastName. 您必须使用RegTable [i] .lastName。 maybe you assign the return value like this: 也许您这样分配返回值:
str = getLastName(str2);
which is wrong. 这是错误的。 you must use strcpy function like this: 您必须使用如下的strcpy函数:
strcpy(str,getLastName(str2));
don't forget to include if you used strcpy. 如果您使用过strcpy,请不要忘记添加。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.