結構體的成員變量在內存中存儲的方式,決定於設定的內存對齊方式是幾字節:gcc編譯默認使用4字節對齊:
1 #include <stdio.h>
2
3 typedef struct test_buf
4 {
5 int a;
6 char c;
7 char buf[8];
8 char *str;
9
10 }buf_t;
11
12 void test_send_srtbuf(void *arg)
13 {
14 //buf_t *revbuf = (buf_t *)arg;
15 buf_t *revbuf = arg;
16 printf("revbuf->a=%d,revbuf->c=%c,revbuf->buf=%s,revbuf->str=%s\n",revbuf->a,revbuf->c,revbuf->buf,revbuf->str);
17 //char *testbuf = arg;
18 //printf("testbuf=%s,testbuf大小爲:%d\n",testbuf,sizeof(testbuf));
19 return;
20 }
21 int main(void)
22 {
23 int len = 0;
24 char revbuf[30] = {0};
25 buf_t buf={
26 .a = 25,
27 .c = 'b',
28 .buf="hello wr",
29 .str = "w143bd",
30 };
31 len = sizeof(buf);
32 printf("len =%d.\n",len);
33 printf("buf.a=%d ,buf.c=%c, buf.buf=%s, buf.str=%s\n",buf.a,buf.c,buf.buf,buf.str);
34 test_send_srtbuf(&buf);
35 return 0;
36 }
上面程序的運行結果:
調用test_send_strbuf時,參數被解析爲了void類型,解析時爲了防止數據錯亂,將它強制類型轉換爲結構體類型,賦值給了另外一個變量,就能夠訪問成員的值。