prophetgoddess

i don't wanna die in here

workin on a dating simulator

podcast

blog

music

My scrobbles

lastfm thingy via here



i don't know why, but for some reason i've always written pointers in C "wrong"

everyone declares a pointer like:

type *pointer= NULL

but i have always written them like

type* pointer = NULL

which has always felt more natural to me. they both work, so it doesn't really matter, but i've been thinking about it because i've been working on some tutorials and i need to standardize my code style. i conceptualize the * as being part of the type and not part of the variable, partly because when you later reference the pointer you reference it like

pointer->member

and not like

*pointer->member

so the pointer operator isn't part of the name.

and you can't do something like

type variable = (type){0}

*variable->member

that's a compile error. not that i can't think of a reason you'd want to do that, but the pointer operator isn't just a thing you can use in-place like any other operator.

i know (at least part of) why you're supposed to write it the normal way, because of a situation like this:

char* pointer = calloc(1, sizeof(type));
*pointer = "c" // this sets a pointer to the string "c"
pointer = "c" // this sets the pointer to the memory address 0x63, which will contain functionally random memory

in this situation, the syntax is inconsistent for the correct behavior. maybe i just haven't written enough C, but i have literally never had to write code that looks like this.

anyone else write pointers wrong? anyone have surprisingly strong opinions about C pointer declaration syntax? i'm probably just going to go back and fix all my pointers to the "correct" syntax before i publish this tutorial.


You must log in to comment.

in reply to @prophetgoddess's post:

I agree with you. I consider "pointerness" to be part of the type, since you include it even in scenarios where you don't include a variable name (e.g. typedef, or writing a function prototype without including the names of parameters)

i mostly wrote in C++, not C, where using pointers to shuffle around objects was the norm, so doing it this way (where the pointer is part of the type) was always way more natural to me than attaching it to the variable

there's maybe an argument to be made that it goes "with the name" because it's like "array-ness" and also because mixed declarations. e.g.

int a=0, *b=&a, c[5] = {0}, *d=c;

however. this sucks

yeah i guess if you think about a pointer as being like an array it makes more sense to go with putting it with the name. i've always conceptualized a pointer as being a pointer to the first item in an array, and square brackets as special syntactic sugar for pointer math.

i guess i meant less "like an array" in terms of that it is, and more in terms of how it's declared? like an array of five int is int a[5]; rather than int[5] a;. but also array syntax is kinda fucked up