C结构体指针访问结构成员-创新互联
1 #include
2
3 struct Payload {
4 char* title;
5 char* data;
6 };
7
8 char* extractData(struct Payload *payload);
9
10 int main(int argc, char const *argv[])
11 {
12 struct Payload payload;
13
14 payload.title = "content-type";
15 payload.data = "text/html";
16
17 char* data = extractData(&payload);
18 printf("%s
", data);
19
20 return 0;
21 }
22
23
24 char* extractData(struct Payload *payload) {
25 if (NULL == payload) {
26 return 0;
27 }
28
29 return payload->data;
30 }
程序2:#include
struct User
{
char* name;
int age;
};
char* name(struct User *user) {
// 传地址,访问成员需要用 ->
return user->name;
}
char* another_name(struct User *user) {
// 或者 dereference 后,得到结构体然后用 .
return (*(user)).name;
}
void main() {
struct User user = {"h", 11};
char* real_name = name(&user);
printf("%s
", real_name);
printf("================
");
char* another_real_name = another_name(&user);
printf("%s
", another_real_name);
printf("%zu
", sizeof(real_name));
}
指针的size 与指向位置实际存储大小无关,而是与操作系统有关,64位机器, 返回8, 32位机器返回4;
创新互联专注于企业营销型网站建设、网站重做改版、襄汾网站定制设计、自适应品牌网站建设、HTML5建站、商城网站建设、集团公司官网建设、外贸营销网站建设、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为襄汾等各大城市提供网站开发制作服务。网站标题:C结构体指针访问结构成员-创新互联
本文链接:http://lswzjz.com/article/doside.html