* * * * *
A breakdown of the triple-star pointer
I few days ago I read “Lessons learnt while trying to modernize some C code
[1]” (via Lobsters [2]) and one of the problems of C stated stood out to me:
“Avoid constructs like char ***. I thought it was a joke, but people do pass
around char *** and it’s insane—almost impossible to comprehend why do you
need a pointer to a pointer to a pointer.” Yes, it happens, but come on! That
doesn't happen often enough to complain about!
And then I found one in my own code [3]!
Sigh.
Okay, at least I can explain why I needed a char ***. It's not insane, and
it's not impossible to comprehend why. I'll start with char *'. In C, that
means “string” (the exceptions are just that—exceptions). We can replace char
* with typedef char *cstring which gets rid of one “*”, leaving effectively
cstring **.
Now, when you see char **, say in int main(int argc,char **argv), it
generally has the meaning of an array of strings: int main(int argc,char
*argv[]). Sometimes it could mean just a pointer to a pointer, but I'm using
the “array of strings” meaning in my code. Translated using the custom type I
defined above, char ** becomes becomes cstring [] and char *** becomes
cstring *[]—a pointer to an array of strings. And this idiom, when it
happens, usually means the callee is going to allocate the memory for the
array of strings and return it via the pointer. Which is exactly what the
function I wrote does.
So when I expect a char *** here, what I'm asking for is a pointer to an
array of strings (aka character pointers or character arrays). The only thing
insane about this is the syntax, and maybe the semantics (pointers and arrays
are near enough the same that it's dangerous) but I've been working with C
long enough that I just kind of accept it.
Now, just don't ask about char ****—that's just silly talk!
[1]
https://dorinlazar.ro/220710-trying-to-modernize-goaccess.en/
[2]
https://lobste.rs/s/r8b8d1/lessons_learnt_while_trying_modernize
[3]
https://github.com/spc476/mod_blog/blob/8eb3f660edd5a35c09616d058307e5a166052c99/src/blog.c#L335
---
Discussions about this page
A breakdown of the triple-star pointer | Lobsters
https://lobste.rs/s/cuaeby
A breakdown of the triple-star pointer | Hacker News
https://news.ycombinator.com/item?id=34920181
Email author at
[email protected]