The difference between SomeClass ** ptr; and SomeClass * ptr;

Sorry this may seem like a honeymoon, but this is a real pain for Google. I use C ++, and although I can get Pointers and References, it is still sometimes quite mysterious to me.

I have some line-by-line code SomeClassName **pointer , and I wonder why there are two asterisks instead?

+4
source share
4 answers

This is much easier to explain with photographs, but we will drop it. Sorry if you already know about this.

A pointer is just a variable that holds a value, just like an int or char. What makes it a pointer is that the value in this variable is an address in the memory of another place.

The examples are simpler. Let them say that we have 3 variables, which we declare as follows:

 int iVar = 42; // int int *piVar = &iVar; // pointer to an int int **ppiVar = &piVar; // pointer to (pointer to an int) 

Our memory may look like this:

 Address Name Value 0x123456 iVar 42 0x12345A piVar 0x123456 0x12345E ppiVar 0x12345A 

So, you know that you can dereference piVar as follows:

 *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 the pointer is still just a variable, we changed the value of what was on the address using *.

Why? One application is allocating 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 look for a pointer to jump to a variable declared in main ()? Hope this is pretty clear.

+14
source

SomeClassName **pointer means "pointer to a pointer to SomeClassName ", and SomeClassName *pointer means "pointer to a SomeClassName object".

Hope this helps,

+8
source

This is a pointer to pointer (s) .

+3
source

Maybe this will help you understand this: a pointer is just a number that refers to a place in memory. Usually this memory has its own object. But in this case, it just has one more number, which refers to another place in memory, which finally has an object that interests you. This can lead to absurdity; you can have SomeClasName ****pointer.

+3
source

Source: https://habr.com/ru/post/1380402/


All Articles