What does ** mean in C++? [duplicate] - c++

This question already has answers here:
Uses for multiple levels of pointer dereferences?
(17 answers)
Pointer to a pointer to a pointer [duplicate]
(4 answers)
Closed 8 years ago.
For example:
bool insertInFront( IntElement **head, int data ){
IntElement *newElem = new IntElement;
if ( !newElem ) return false;
newElen->data = data;
*head = newElem; // Correctly updates head
return true;
}
I am new to C++, coming from Java. I get the * for indirection syntax, but ** is not listed on this page: http://en.wikipedia.org/wiki/Operators_in_C_and_C++#Member_and_pointer_operators
I found this example on page 28 of Programming Interviews Exposed
Update
I realize that this question is naive, and I probably could have found an answer through other means. Obviously, I am new to the language. Still, asking "What does ** mean?" is not well supported online for someone who does not know that ** is a pointer operation. There are very few relevant results when searching C ** syntax or C++ ** meaning. Additionally, using ctrl + f to search ** in the wiki page above, and other documentation, doesn't return any matches at all.
I just wanted to clarify, from a beginner's perspective, that this question is hard to distinguish from the duplicates. Of course, the answer is the same :-) Thank you for the help.

There is no specific ** operator in C++, instead it's two separate asterisks, and asterisks in a declaration denotes pointer declaration.
So in the declaration
IntElement **head
the argument head is declared to be a pointer to a pointer to IntElement.

Its meaning:
int a; // integer
int *ptrA = &a // pointer to a integer
int **PtrPtrA = &ptrA // point to pointer to a integer
How can it be used:
void function_nochange(int *pA ) { pA = &b; }
void function_change (int **ppA) { *ppA = &b; }
int a;
int b;
void test()
{
int *ptrA = &a
function_nochange(ptrA)
// here ptrA still point to int a since ptrA was copied
function_change(&ptrA)
// here ptrA point to int b since ptrA was passed as pointer
}

**VariableName means pointer to pointer(a chain of pointers) in C++
You can find good tutorials here :
http://www.tutorialspoint.com/cplusplus/cpp_pointer_to_pointer.htm
http://www.codeproject.com/Articles/4894/Pointer-to-Pointer-and-Reference-to-Pointer

Related

Changing the address a pointer is pointing to [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want to change different pointer (different types), that they point to NULL/0/nullptr..., but I have to use a variable to do this! Generally I understand pointers and I know what the problem is, but I don't know how to solve it.
So I need something like
int NULLPOINTER = nullptr; // data type can change if needed
int* myIntPointer = NULLPOINTER;
float* myFloatPointer = NULLPOINTER;
foo* myFooPointer = NULLPOINTER;
As shown above, this is not possible because of the invalid conversion error (int to int*/float*/foo*).
So how can I archiv this?
As requested a more complex example for clarification:
class foo
{
float floatVar;
};
class bar
{
char charVar;
};
void changeSomething(bar* pBarTmp)
{
/* pGlobal is a member of another class and the type is depends on the method */
pGlobal = pBarTmp;
}
int main()
{
/* Working just fine */
int var = 1;
int *pointer = &var;
/* Also working fine */
foo *pointer = 0; //nullptr or NULL or __null (compiler dependend)
/* Not working because newAddress is int and not bar* / foo* / int* */
int newAddress = 0;
// Only one of the following is present, it depends on the
// method/class (just for visualization)
bar *pointer = newAddress;
foo *pointer = newAddress;
int *pointer = newAddress;
changeSomething (pointer);
}
I am not allowed to change int newAddress; into int* newAddress;. Overall I won't use something else than NULL / 0 / nullptr / ...
Another difficulty is, that I cannot use reinterpret_cast cause of coding guidelines.
int* p3 = 1; //Error invalid conversion from int to int
You can directly set the address of a pointer in C++
int* p3 = reinterpret_cast<int*>( 0x00000001 );
But its not good idea since you dont know where the pointer points in memory and de-referencing would lead to undefined behavior.
Its invalid conversion because 1 has type int and it's not possible to assign to pointer variable int * without cast.
int* p2 = 0; //p is a NULL-pointer
Pointers pointing to null should be initialized
int* p2 = nullptr;
instead of
int* p2 = 0;
Since C++11 you can create an instance of std::nullptr_t and assign it to pointers.
std::nullptr_t initAddr;
int* p2 = initAddr;
C++11 came with nullptr, and nullptr has type std::nullptr_t. You can create an instance of this and assign:
int* p1;
char* p2;
double* p3;
std::nullptr_t newAddress;
p1 = newAddress;
p2 = newAddress;
p3 = newAddress;
Demo
This satisfies having your NULL in a variable.
Changing the adress a pointer is pointing to
My goal is to change the adress of different pointer types to NULL
By assignment:
int* p = nullptr;
and I have to use a variable to do this.
int newAdress = 0;
int* p2 = newAdress;
The bug here is that newAdress has the wrong type. The compiler helps you out by telling you that is wrong. You will need to use a pointer (of compatible type) variable to assign a pointer:
int* newAdress = nullptr;
// ^ see here, a pointer
int* p2 = newAdress;
int* p3 = 1;
This assignment makes little sense in most cases. 1 is not null, nor is there usually a guarantee that there is an int object at that memory location.
Nevertheless, there are some special cases where you need a particular address value. That can be achieved with casting:
int* p3 = reinterpret_cast<int*>(1);
If you don't know of such cases, then you don't need to do it. If you don't have such case, then using pointer to the arbitrary memory location has undefined behaviour.
You have to understand that int* ≠ int. You shouldn't directly change the address. That seems pointless, since every program run variables are saved in different parts of memory with different addresses.
It only works with NULL, which is the same as 0, but should be avoided in C++ 11, where you should use nullptr for safety.
What you can do is set the address with the address-of-operator &:
int a;
int* b = &a;

what's the difference between these two pointer code [duplicate]

This question already has answers here:
Pointer vs. Reference
(12 answers)
Closed 6 years ago.
I found these two different sources, but they do the exact same thing. I was wondering if there is a difference or not but I couldn't figure it out.
Can anyone tell me the difference and when should I use which?
this is the first one:
void function1(int *x) {
*x = 100;
}
int main() {
int var1 = 10;
function1(&var1);
cout << var1 << endl;
}
and this is the second one:
void function2(int &x) {
x = 100;
}
int main() {
int var2 = 10;
function2(var2);
cout << var2 << endl;
}
int *x is a pointer whereas int &x is a reference. Probably the biggest difference is that you can't change where reference is pointing to.
The first is a pointer, the second is a reference. The ideas have some similarities, but there are also differences.
A pointer is a C and C++ mechanism and a bit more "pure" but gives you more posibilies for advanced concepts like pointer arithmetics. References are C++ only and are more safe and more implicit, as a reference is used with the same syntax as a normal varible while using the referenced one. A pointer is more explicit if you want to use or change its value, as you have to explicitely dereference it using *var, and explicitely have obtain it.

Why pointer to pointer?

A very general question: I was wondering why we use pointer to pointer?
A pointer to pointer will hold the address of a pointer which in turn will point to another pointer. But, this could be achieved even by using a single pointer.
Consider the following example:
{
int number = 10;
int *a = NULL;
a = &number;
int *b = a;
int *pointer1 = NULL;
pointer1 = b; //pointer1 points to the address of number which has value 10
int **pointer2 = NULL;
pointer2 = &b; //pointer2 points to the address of b which in turn points to the address of number which has value 10. Why **pointer2??
return 0;
}
I think you answered your own question, the code is correct, what you commented isn't.
int number = 10; is the value
int *pointer1 = b; points to the address where int number is kept
int **pointer2 = &b; points to the address where address of int number is kept
Do you see the pattern here??
address = * (single indirection)
address of address = ** (double indirection)
The following expressions are true:
*pointer2 == b
**pointer2 == 10
The following is not!
*pointer2 == 10
Pointer to pointer can be useful when you want to change to what a pointer points to outside of a function. For example
void func(int** ptr)
{
*ptr = new int;
**ptr = 1337;
}
int main()
{
int* p = NULL;
func(&p);
std::cout << *p << std::endl; // writes 1337 to console
delete p;
}
A stupid example to show what can be achieved :) With just a pointer this can not be done.
First of all, a pointer doesn't point to a value. It point to a memory location (that is it contains a memory address) which in turn contains a value. So when you write
pointer1 = b;
pointer1 points to the same memory location as b which is the variable number. Now after that is you execute
pointer2 = &b;
Then pointer2 point to the memory location of b which doesn't contains 10 but the address of the variable number
Your assumption is incorrect. pointer2 does not point to the value 10, but to the (address of the) pointer b. Dereferencing pointer2 with the * operator produces an int *, not an int.
You need pointers to pointers for the same reasons you need pointers in the first place: to implement pass-by-reference parameters in function calls, to effect sharing of data between data structures, and so on.
In c such construction made sense, with bigger data structures. The OOP in C, because of lack of possibility to implement methods withing structures, the methods had c++ this parameter passed explicitly. Also some structures were defined by a pointer to one specially selected element, which was held in the scope global to the methods.
So when you wanted to pass whole stucture, E.g. a tree, and needed to change the root, or 1st element of a list, you passes a pointer-to-a-pointer to this special root/head element, so you could change it.
Note: This is c-style implementation using c++ syntax for convienience.
void add_element_to_list(List** list, Data element){
Data new_el = new Data(element); // this would be malloc and struct copy
*list = new_el; //move the address of list, so it begins at new element
}
In c++ there is reference mechanismm and you generally you can implement nearly anything with it. It basically makes usage of pointers at all obsolete it c++, at least in many, many cases. You also design objects and work on them, and everything is hidden under the hood those two.
There was also a nice question lately "Why do we use pointers in c++?" or something like that.
A simple example is an implementation of a matrix (it's an example, it's not the best way to implement matrices in C++).
int nrows = 10;
int ncols = 15;
double** M = new double*[nrows];
for(unsigned long int i = 0; i < nrows; ++i)
M[i] = new double[ncols];
M[3][7] = 3.1416;
You'll rarely see this construct in normal C++ code, since C++ has references. It's useful in C for "passing by reference:"
int allocate_something(void **p)
{
*p = malloc(whatever);
if (*p)
return 1;
else
return 0;
}
The equivalent C++ code would use void *&p for the parameter.
Still, you could imagine e.g. a resource monitor like this:
struct Resource;
struct Holder
{
Resource *res;
};
struct Monitor
{
Resource **res;
void monitor(const Holder &h) { res = &h.res; }
Resource& getResource() const { return **res; }
}
Yes, it's contrived, but the idea's there - it will keep a pointer to the pointer stored in a holder, and correctly return that resource even when the holder's res pointer changes.
Of course, it's a dangling dereference waiting to happen - normally, you'd avoid code like this.

Difference between & and * in function parameters [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
difference between a pointer and reference parameter?
Using C++ i'm wondering what's the difference in the use of & and * in parameters?
For example:
void swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
That apparently would swap the integers a and b. But wouldn't the following function do exactly the same?
void swap(int *a, int *b)
{
int temp = *b;
*b = *a;
*a = temp;
}
I was just wondering when it is appropriate to use each one, and perhaps the advantages of each one.
The difference between pointers and references is that pointers can point to "nothing", while references cannot. Your second sample should null-check pointers before dereferencing them; there is no need to do so with references.

Can someone help me understand this? int *& pr [duplicate]

This question already has answers here:
What does *& mean in a function parameter
(5 answers)
Closed 10 years ago.
I found this in a final exam:
int a = 564;
int* pa = &a;
int *& pr = pa;
cout << *pr;
According to the multiple choice answer, the code is valid, and displays the value of a.
But I'm confused about evaluation and precedence for line 3. Order of operations for C states that * and & have the same order. So, would it then be int *(&pr)? How can this be described in words?
Thank you.
The third line defines a pointer reference (or a reference to a pointer, if you want). Assigning it to a pointer makes pr to actually be an alias to pa, and when evaluated, it points where pa points to, that is, a.
In the declaration of a variable, * and & don't have the meaning of operators, so precedence doesn't make sense here.
It's a reference to a pointer. In C, you would express that as a pointer to a pointer.
You could write something like this:
// C++ style
void update_my_ptr(int*& ptr) { ptr = new int[1024]; }
// C style
void update_my_ptr_c(int **ptr) { *ptr = malloc(1024 * sizeof(int)); }
int main()
{
int *ptr;
update_my_ptr(ptr);
// Here ptr is allocated!
}
Line three creates a reference (read: alias) of a pointer to an int. If you were to set pr to 0, pa would also be equal to 0 (and vice-versa).