As per the title. I see certain people declaring a pointer as char* s
, and others declaring it as char *s
. Also I see some people doing, say, s = (char*) malloc(5)
instead of doing *s = malloc(5)
. Is there a difference between that as well? Apologies if this question is repeated, I understand the concept of pointers, but have great difficulty understanding the syntax used to represent pointers in C.
Asked
Active
Viewed 641 times
0

Wet Feet
- 4,435
- 10
- 28
- 41
-
7No difference at all. – haccks Mar 07 '16 at 11:13
-
1You do not need the cast for `malloc` – Ed Heal Mar 07 '16 at 11:14
-
2`*s = malloc(5)` would be wrong, unless `s` is `char**`. And `malloc()` shouldn't be cast since it's not needed. – Sami Kuhmonen Mar 07 '16 at 11:15
-
So if I do something like `char* s = null;` and `char *t = null;`, `s == t` will return true? – Wet Feet Mar 07 '16 at 11:15
-
1@WetFeet If you mean `NULL`, instead of `null`, then yes. – Spikatrix Mar 07 '16 at 11:17
1 Answers
6
There's no difference.
A sort of convention has grown up: folk like to think of char*
as being the type for s
(which is, of course, a pointer); this can make source code more readable.
But really char
is the type, and *s
the variable. You can see this by writing
char* s, t;
s
is a pointer, but t
is a plain-old char
. If you wanted both s
and t
to be pointers, you'd have to write
char *s, *t;
or the obfuscated
char* s, *t;

Bathsheba
- 231,907
- 34
- 361
- 483
-
1
-
I like to think 'char*' as the type, and 's' as the variable name, +1 :D – Netwave Mar 07 '16 at 11:18
-
@MartinJames: It's a dangerous question to answer (i) possibly a duplicate and (ii) borderline opinion-based. – Bathsheba Mar 07 '16 at 11:20
-
Saying that `char` is the type `*s` is the variable isn't really sensible either. It doesn't make sense for `void *p`, `sizeof (T *)`, etc. I think it's better to say that `*` binding with the variable name is a quirk of the C grammar rather than trying to rationalize it. – jamesdlin Mar 07 '16 at 11:21