Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between SomeClass **ptr; and SomeClass *ptr;

Tags:

c++

c

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?

like image 589
chrisburke.io Avatar asked Nov 28 '22 14:11

chrisburke.io


1 Answers

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.

like image 96
JoeFish Avatar answered Dec 18 '22 08:12

JoeFish