[英]Declaration of pointers in c
我正在使用gcc 4.8.1,我無法理解以下程序的輸出。
#include<stdio.h>
int main()
{
char* a, b, c;
int* d, e, f;
float* g, h, i;
printf("Size of a %zu and b %zu and c %zu \n", sizeof(a), sizeof(b), sizeof(c));
printf("Size of d %zu and e %zu and f %zu and int is %zu \n", sizeof(d), sizeof(e), sizeof(f), sizeof(int*));
printf("Size of g %zu and h %zu and i %zu and float is %zu \n", sizeof(g), sizeof(h), sizeof(i), sizeof(float));
return 0;
}
Size of a 4 and b 1 and c 1
Size of d 4 and e 4 and f 4 and int is 4
Size of g 4 and h 4 and i 4 and float is 4
我的問題是為什么b
和c
不是char*
類型,而int
和float
情況也是如此。 我想知道C語法如何拆分聲明。
在像這樣的宣言中
char* a, b, c;
只有char
類型用於所有變量,而不是它是否是指針( *
符號)。 如果這樣使用(等效)語法使其更清晰:
char *a, b, c;
要定義3個指針:
char *a, *b, *c;
或者在經常使用多個指向char的指針的情況下,可以執行typedef:
typedef char* char_buffer;
char_buffer a, b, c;
問題是你使用了不好的聲明風格
這些聲明
char* a, b, c;
int* d, e, f;
float* g, h, i;
相當於
char* a;
char b, c;
int* d;
int e, f;
float* g;
float h, i;
char
類型的對象的sizeof
等於1
而系統中的sizeof( char * )
等於4.因此輸出正確
Size of a 4 and b 1 and c 1
由於系統中的sizeof( int )
和sizeof( float )
等於4
因此您將獲得輸出
Size of d 4 and e 4 and f 4 and int is 4
Size of g 4 and h 4 and i 4 and float is 4
我說你使用糟糕的編程風格,因為你正在使用的聲明就像這樣
char* a, b, c;
不符合C語法。 C語法拆分聲明說明符中的聲明(對於上面的語句是關鍵字char
)和聲明符(在上面的語句中它們是*a
, b
和c
)。 所以你應該遵循C語法。 在這種情況下,您的代碼將更加清晰。
char *a, b, c;
(例如比較
char unsigned* c;
和
char unsigned *c;
什么聲明更清楚?)
不要忘記你的代碼可以讀取程序員,例如不知道C但知道C#。 在這種情況下,他們將簡單地混淆。 當您在帖子中考慮這些聲明時,他們會以錯誤的方式考慮聲明。
char* a, b, c;
這里, a
的類型為char *
, b
和c
的類型為char
。 同樣也適用於其他人。
在您的平台中就是這種情況, int
和float
占用4個字節,就像指針的大小[表示sizeof(int)
和sizeof(float)
與sizeof(int *)
和sizeof(float *)
相同]而, char
的大小為1。
因此,當sizeof(b)
給出1 [ b
是char
類型]時,你的sizeof(a)
產生4 [ a
是指針]。
e
, f
是int*
。 他們不是。 h
, i
是float *
。 再說一遍,他們不是。 程序中唯一的指針是a
, d
和g
。
只是在您的平台上, int *
, float *
, int
和float
都具有相同的大小。
char* a, b, c;
*a
是一個char(當a
本身有效時)
b
是一個char
c
是一個char
[評論太久了]
只是為了完整性:要定義三個char
指針(而不是一個char
指針和兩個char
)我會去:
char * a; /* This is used to do ... */
char * b; /* This is used to do ... */
char * c; /* This is used to do ... */
你需要為你想要指定的每個指針添加一個單獨的星號*
(因為語言語法是這樣說的):
// declare 3 pointers
char *a, *b, *c;
為了使這個更清楚(對我自己),我更喜歡將星號直接放在變量名之前,而不是直接在類型說明符之后。
// I prefer this:
char *d;
// instead of this:
char* e;
這不會因為你的機器上的int
和float
而變得很明顯,因為它們的大小與它們各自的指針類型相同(4)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.