0

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.

Wet Feet
  • 4,435
  • 10
  • 28
  • 41

1 Answers1

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
    Hard to believe that this is not a multi-dup. – Martin James Mar 07 '16 at 11:18
  • 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