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 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