Reputation: 1507
Sorry that this may seem like a rookie question, but it's a real pain to Google. I am using C++ and while I can get by Pointers and References are still sometimes quite cryptic to me.
I have some code, along the lines of SomeClassName **pointer
and I am wondering why are there two asterisk instead of one?
Upvotes: 4
Views: 226
Reputation: 3100
It's a lot easier to explain with pictures, but we'll give it a go. Apologies if you already know some of this.
A pointer is just a variable that holds a value, just like an int or a char. What makes it a pointer is the fact that the value in that variable is the address in memory of some other place.
Examples are easier. Let's say we have 3 variables that we declare thusly:
int iVar = 42; // int
int *piVar = &iVar; // pointer to an int
int **ppiVar = &piVar; // pointer to (pointer to an int)
Our memory might look like this:
Address Name Value
0x123456 iVar 42
0x12345A piVar 0x123456
0x12345E ppiVar 0x12345A
So, you know you can dereference piVar like this:
*piVar = 33;
and change the value of iVar
Address Name Value
0x123456 iVar 33
0x12345A piVar 0x123456
0x12345E ppiVar 0x12345A
You can do the same with ppiVar:
*ppiVar = NULL;
Address Name Value
0x123456 iVar 33
0x12345A piVar 0
0x12345E ppiVar 0x12345A
Since a pointer is still just a variable, we changed the value of what was at the address using *.
Why? One application is to allocate memory from a function:
void MyAlloc(int **ppVar, int size)
{
*ppVar = (int *)malloc(size);
}
int main()
{
int *pBuffer = NULL;
MyAlloc(&pBuffer, 40);
}
See how we dereference the pointer to get to the variable as declared in main()? Hope that's fairly clear.
Upvotes: 14
Reputation: 5470
Maybe this will help you understand it: a pointer is just a number that refers to a place in memory. Usually that memory has your object in it. But in this case, it just has another number in it, that refers to yet another place in memory, that finally has the object you're interested in. This can chain on to the point of absurdity; you could have SomeClasName ****pointer.
Upvotes: 3
Reputation: 2673
SomeClassName **pointer
means "pointer to pointer to SomeClassName
", while SomeClassName *pointer
means "pointer to a SomeClassName
object".
Hope that helps,
Upvotes: 8