jump to navigation

c-faq review and a chinese translation (1.5) January 25, 2007

Posted by TSAI HONG-BIN in Programming.
trackback

please refer to http://c-faq.com/decl/charstarws.html

1.5 What’s wrong with this declaration?

char* p1, p2;

I get errors when I try to use p2.

Nothing is wrong with the declaration–except that it doesn’t do what you probably want. The * in a pointer declaration is not part of the base type; it is part of the declarator containing the name being declared (see question 1.21). That is, in C, the syntax and interpretation of a declaration is not really

type identifier ;

but rather

base_type thing_that_gives_base_type ;

where “thing_that_gives_base_type”–the declarator–is either a simple identifier, or a notation like *p or a[10] or f() indicating that the variable being declared is a pointer to, array of, or function returning that base_type. (Of course, more complicated declarators are possible as well.)

 

In the declaration as written in the question, no matter what the whitespace suggests, the base type is char and the first declarator is “* p1”, and since the declarator contains a *, it declares p1 as a pointer-to-char. The declarator for p2, however, contains nothing but p2, so p2 is declared as a plain char, probably not what was intended. To declare two pointers within the same declaration, use

char *p1, *p2;

Since the * is part of the declarator, it’s best to use whitespace as shown; writing char* invites mistakes and confusion.

See also question 1.13.

Additional links: Bjarne Stroustrup’s opinion

 

 

這樣宣告有什麼錯?

char* p1, p2;

為什麼我在使用 p2 時收到錯誤訊息

 

 

宣告的部份沒有錯,除了這樣宣告可能不會如你所想像的樣子運作。 * 用意在宣告指標,它不是 base type (按:指int, char, bool, …etc.),而是包含欲宣告的型態名字 (按:指 p1, p2) declarator。也就是說,在C語言裡,對於宣告的語法和解讀不是單單

type identifier;

而是

base_type thing_that_gives_base_type;

這裡的 “thing_that_gives_base_type”若不是單純的識別符 (identifier) ,就是類似 *p, a[10], f() (按:指標、陣列和函式) 的註記,用來指出欲宣告的變數,會指向base_type型態、是一個base_type型態的陣列或base_type型態的函式回傳值。(當然,也可能有更複雜的declarators)

在問題裡的宣告,不論看到幾個空格, base type char 而第一個 declaratory “* p1”,既然declarator 包含 *,它會將p1宣告為char的指標 (按:指向一個char 型態的資料),而p2沒有declarator,它被宣告為單純的char型態,或許不是提問人的原意。要在一行裡宣告兩個指標,應該寫為

char *p1, *p2;

既然 * declarator 的一部份,使用時的空格也最好如上所示(按:跟在變數的前面),寫成 char* 會導致錯誤或疑惑

Advertisements

Comments»

No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: