H-how did this meme clear up a confusion I have with ** pointers after all these years?
They’re just pointer pointers!
Dang, that is so cool C can do that.
If you’ve never seen this before, I think it’s transformative to how you read C/C++ declarations and clearer up a lot of confusion for me when I was learning.
That’s actually a pretty good representation.
I’m a simple man. I see Anya, I upvote.
int** int* interesting
Wait we can have pointers to other pointers? Wouldn’t that be redundant?
In CUDA, the corresponding malloc
cannot return the pointer to the allocated memory as runtime CUDA functions all return error codes instead. So the only way to “return” the pointer then without a return statement is to have a pointer given to that function by address, which means that you’ll have a pointer-to-pointer among its arguments.
So it’s sort of like “proxying” through pointers to enforce memory isolation?
I’m not entirely sure what you mean by memory isolation here, but the basic idea is that if you have a pointer to something then you know where it is located in memory and you can write in it, that’s the whole idea of passing by address in C.
Now pointers themselves are merely variables. Yes they have a special meaning, they “point” to something and you can dereference them with the *
operator, but at the end of the day they’re still variables. They have a physical existence in memory or CPU registers, and their content is simply the address to which you want to point. Once you accept this, then the idea of the address of a pointer (ie the location of the variable you’re calling “pointer”, and not the address it contains) is not strange anymore and you can perfectly have a pointer-to-pointer in order to, among other things, pass pointers by address.
char**
So that you can have an array of strings. It’s useful to remember that in C arrays and pointers are exactly the same thing, just syntax sugar for however you want to look at it. There are a few exceptions where this isn’t true however:
- Argument of the
operator
- Argument of
sizeof
- C11 has
alignof
which decay is a no-no - When it’s a string literal of
char[]
or wide literal ofwchar_t[]
, so likechar str[] = "yo mama";
But int**
is just an array of int*
, which likewise int*
can just be an array of int
. In the picture here, we have int** anya
that is an array of int*
with a size of 1, int* anya
that is an array of int
with a size of 1, and then of course our int
there being pointed to by int* anya
.
I guess this is beating a dead horse but you can have pointers to pointers for 2D arrays.
The first pointer tells you which coulm you’re on. The second pointer tells you which is the first object of each column. That way you can iterate the columns without loosing a reference to the current column you’re standing on.
Here’s a true example from my collections library:
This one uses a bit safer reference to a pointer:
Basically it allows me to modify a pointer easily.