C结构体指针访问结构成员

 1 #include <stdio.h>
 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\n", 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 <stdio.h>

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\n", real_name); printf("================\n"); char* another_real_name = another_name(&user); printf("%s\n", another_real_name); printf("%zu\n", sizeof(real_name)); }

 

指针的size 与指向位置实际存储大小无关,而是与操作系统有关,64位机器, 返回8, 32位机器返回4;

 

posted @ 2021-08-22 19:18  Joynic  阅读(616)  评论(0编辑  收藏  举报