1

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.

5
  • 7
    No difference at all.
    – haccks
    Mar 7, 2016 at 11:13
  • 1
    You do not need the cast for malloc
    – Ed Heal
    Mar 7, 2016 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. Mar 7, 2016 at 11:15
  • So if I do something like char* s = null; and char *t = null;, s == t will return true?
    – Wet Feet
    Mar 7, 2016 at 11:15
  • 1
    @WetFeet If you mean NULL, instead of null, then yes.
    – Spikatrix
    Mar 7, 2016 at 11:17

1 Answer 1

7

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;

4
  • 1
    Hard to believe that this is not a multi-dup. Mar 7, 2016 at 11:18
  • I like to think 'char*' as the type, and 's' as the variable name, +1 :D
    – Netwave
    Mar 7, 2016 at 11:18
  • @MartinJames: It's a dangerous question to answer (i) possibly a duplicate and (ii) borderline opinion-based.
    – Bathsheba
    Mar 7, 2016 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 7, 2016 at 11:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.