출처 : http://c-faq.com/
Q: What's wrong with this declaration?
char* p1, p2;
I get errors when I try to use p2.
A: 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
'엔지니어' 카테고리의 다른 글
C-FAQ 어찌되었건 pointer 쓰면 정말 좋은가? (7) | 2012.07.12 |
---|---|
C FAQ (malloc 오류) (7) | 2012.07.12 |
[Linux/Unix]포트가 열렸는지 여부확인 (166) | 2012.07.12 |
개발자가 놓치지 말아야 할 (명저) 베스트 70 (259) | 2012.07.11 |
message queue늘리는 방법(Solaris) (274) | 2012.07.11 |