簡體   English   中英

c中的指針聲明

[英]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

我的問題是為什么bc不是char*類型,而intfloat情況也是如此。 我想知道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 )和聲明符(在上面的語句中它們是*abc )。 所以你應該遵循C語法。 在這種情況下,您的代碼將更加清晰。

char *a, b, c;

(例如比較

char unsigned* c;

char unsigned *c;

什么聲明更清楚?)

不要忘記你的代碼可以讀取程序員,例如不知道C但知道C#。 在這種情況下,他們將簡單地混淆。 當您在帖子中考慮這些聲明時,他們會以錯誤的方式考慮聲明。

char* a, b, c;

這里, a的類型為char *bc的類型為char 同樣也適用於其他人。

在您的平台中就是這種情況, intfloat占用4個字節,就像指針的大小[表示sizeof(int)sizeof(float)sizeof(int *)sizeof(float *)相同]而, char的大小為1。

因此,當sizeof(b)給出1 [ bchar類型]時,你的sizeof(a)產生4 [ a是指針]。

  • 不要認為efint* 他們不是。
  • 不要認為hifloat * 再說一遍,他們不是。

程序中唯一的指針是adg

只是在您的平台上, int *float *intfloat都具有相同的大小。

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;

這不會因為你的機器上的intfloat而變得很明顯,因為它們的大小與它們各自的指針類型相同(4)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM