difference b/w **ptr and *ptr - c++

The basic knowledge i have about pointers is that they point to a memory location and that they can be used for changing and extracting the values stored at that address.
for eg.
int a=5;
int *b;
b=&a;
Now here b points to the memory location of a.
cout<<*b; //gives the output 5
cout<<b; //outputs the address of a.
Basically for the purpose and passing the values by reference in functions and in data structures such as linked list and trees.
main()
{
node *head=NULL;// A pointer head of type node structure
add(&head,2); //adds the value to linked list
}
void add(node**head,int data)
{
//adds value into node
}
Can any one tell me why the &head has been received as **head in the add() function.
Also, what difference would it have made had it been received as *head?
when i print the value of **head it gives me a compiler error.

type of head is node*, when you get address of node* (&head), type of it is node**.
Difference between node** and node* is same as int* and int. One of them defines a pointer to other type.
add method gets a pointer because it might change the value of head. if *head is NULL, it should create a new node and assign head to address of this new node. if it inputted just node head, assigning head = malloc(...) wouldn't work since c is pass by value and it just assigns the "head" defined within the function, not head in the main. but if gets the address of the head in the main, it can freely alter it by accessing it like *head = malloc(...)
head is a pointer so you can't really print its value (well, you can if you cast it but it wouldn't be anything meaningful). You probably need to cast it

int *p; // p -> is a pointer to an int, *p -> integer contained in address pointed by p.
similarly
int **p2; // p2 -> a pointer to a pointer to an it, *p2 -> pointer to a int, **p2 int.
If you are confused, you can remember it as a covering rule. If you want to know what *p is, just cover *p ( we have int so it is an int ), if you to know what *p2 is, just cover it ( we have int * meaning it is a pointer to an int ).

This is my answer to another question: https://stackoverflow.com/a/20818342/2805305
The question was about an error the op got, but in my answer I explain exactly what you need to know.

Related

Confusion about node pointer assignment

My code looks like this:
#include <iostream>
struct Node {
double data;
Node* next;
};
int main(){
Node* a;
a = new Node;
}
I am having a hard time understanding why the assignment would work for a pointer. Because a is type Node* but the new node is type Node.
At the beginning of my class, I was taught that pointer assignment needs to always be an address.
For example:
int * x;
int y = 5;
This would be allowed:
x = &5;
But this wouldn't:
x = y;
So, by that same logic, shouldn't the assignment of Node* a; be:
a = &(new Node);
Instead of:
a = new Node;
?
When you call new, it creates a new object and returns a pointer to that object. It is quite common to store that pointer in a pointer variable. You would use & new(...) if it returned a reference to the newly-created object. But it doesn't.
but the new Node is type Node.
is absolutely wrong. This is not Java. new Node returns a pointer to a freshly allocated on heap Node.
First of all, every assignment requires correct type. Either you provide left argument of the exact same type as the variable you assign to, or of a type you can convert from. E.g.
int x = 5; //here x is a type of int and 5 is also an int
or
double w = 3; //here w is a type of double and 3 is again int but int can be converted to double
in contrary
int z = 3.2; //won't compile because 3.2 is a float and floats have to be explicitly casted to ints.
Now, with your code, Node* is a type you read as Node pointer and new allocates memory on heap, creates new object and return its address which in this case is also Node pointer. Types match and everything works.

C++ object declaration confusion?

I'm trying to implement a BST in C++, and I came across these two ways of creating a node:
node* z = new node();
z->key = d;
z->left = NULL;
z->right = NULL;
and then this:
node* y = NULL;
node* x = root;
node* parent = NULL;
What is the difference in calling the new operator or not?
EDIT
so for example, whats the difference between:
node* q = new node();
and
node* q;
and why would you choose one way or the other? Is there an advantage for one way or the other?
To answer the question in the comment, yes there is a difference.
When you do node* q = new node() you declare a pointer to a node object, and then at runtime dynamically allocate memory enough for one node object, and calls the default constructor (alternatively, value initializes the object, it depends on the class/struct), and finally you assign the pointer to the newly allocated object to q.
When you do node* q; you just declare a pointer to a node object, and that's it. What the pointer will be pointing to depends on where you declare the pointer: If you declare it as a global variable, it is initialized to zero, and becomes a null pointer; If you declare it as a local variable its value is indeterminate, and will in reality seem to be random. Neither is a valid pointer, and dereferencing it will lead to undefined behavior. There is also a third alternative, and that's where you declare node* q; as a member variable in a class or struct, then the initial value depend on how the class/structure is created and initialized (for example if the structure is value initialized, if there's a constructor that initializes it, etc.).
I'm pretty sure (Someone correct me if i'm wrong), using the new operator allocates dynamic memory for that variable. The variables will most likely already have some garbage value assigned to them that gets overridden when you assign a new value to them. Whereas assigning it NULL just assigns it whatever the NULL value is (probably 0000000).

issues in understanding pointers

The following codes are from the book Programming Interviews Exposed
I am having problem to understand the concept of pointers. Why can't we use the code no. 1.
Code no. 1
bool insertInFront( IntElement *head, int data )
{
IntElement *newElem = new IntElement;
if( !newElem ) return false;
newElem->data = data;
head = newElem; // Incorrect!
return true;
}
Code no. 2
bool insertInFront( IntElement **head, int data )
{
IntElement *newElem = new IntElement;
if( !newElem ) return false;
newElen->data = data;
*head = newElem; // Correctly updates head
return true;
}
In code 1, you are assigning the pointer location of newElem to the local copy of head. When the function returns, head is destroyed, and you will have a memory leak (you lose the pointer to newElem, leaving you with no way to delete it.) You've only changed the function's local copy of the pointer, the caller's copy is unaffected.
In code 2, head is a pointer-to-a-pointer. You don't have just a pointer, you actually have a pointer to the caller's pointer. This allows you to alter the caller's pointer, storing the pointer to newElem When the function returns, head is destroyed, but it's only the pointer-to-a-pointer. The original pointer is intact in the caller's scope.
Say you are calling function 1 as:
insertInFront(H, data);
Upon calling of a function, the computer makes duplication of arguments, then release them when the function returns. So in code No.1, head=newElem assigned the address of newElem to head(which is a duplicate of H), then released head, and the address of newElem is lost forever.
In code No.2, however, the function should be called as:
insertInFront(&H, data);
This means the ADDRESS of H is duplicated to head, and the address of newElem is assigned to *head, i.e. where head is pointing, which results in H. In this way you get the address of newElem after the function returns.
The concept of pointers are very complicated. Basically the way you need to think about pointers are that they are 'values' themselves. so:
*head = some_memory_address_that_points_to_head;
could be thought of as:
int im_a_pointer_to_head = some_memory_address_value_to_head;
So if we apply this same concept to your first function:
bool insertInFront(int im_a_pointer_to_head, int data)...
You are essentially passing in a copy of the value of your head pointer, changing it within the function only changes the temporary copy made for this function and does not actually change where the original pointer is pointing to.
The second function solves this because you are actually passing in the copy of the pointer that is pointing to the pointer that is pointing to the head (try saying that 3 times fast!). In this case, you are not changing the copied value, but instead are changing where the actual pointer is pointing to.
To change the value of anything passed via a function argument (and have that change persisted) outside of the function call, you MUST have the memory address of whatever it is whose value you want to change. This is another way of saying that you must "pass by reference" instead of "pass by value" -- otherwise pass by value will cause the function to just alter the COPY.

Why use **head (and not *head) in RemoveHead(node) function?

In most of the explanations in the book the author insists of using **list passing instead of *list, however as per my understanding I feel there is nothing wrong in *list. Please someone explain me in detail if i am wrong. For example, to delete head of a linked list, the author says the below code is wrong.
void RemoveHead(node *head)
{
node *temp = head-> next; /* line 1 */
free(head);
head = temp;
}
Instead he says the below code must be used
void RemoveHead(node **head)
{
node *temp = (*head)-> next;
free(*head);
*head = temp;
}
In your first example:
head = temp;
Does nothing outside the function, it only sets the local variable head to temp inside the function. Whatever variable the caller passed in will remain unchanged. The author is correct, you need to use pointers or (better) references (if you're using C++).
Well. When you want to modify a integer variable inside a function, you pass it by reference. That is, you pass its address.
int x = 5;
void modify_value (int* x)
{
(*x) = 7; // is not 5 anymore
}
With pointers is the same. If you want to modify a pointer. You have to pass it by reference. That is, you have to pass its address. Which is a pointer to a pointer.
int* ptr_x = &x;
void modify_pointer (int** ptr_x)
{
*ptr_x = NULL; // is not &x anymore
}
Author is right. ** is effectively pass by reference (i.e. you can change 'head').
In your version (pass by value), head remains unchanged in the calling code.
When passing a node* as the argument, you can free, and modify the contents of the memory address pointed by that pointer. However, modifications performed on the pointer itself will not be seen from outside the function, since the pointer is passed by value.
On you second example, since you are passing a pointer to the head pointer, you can actually modify the actual head pointer, not just the memory pointed by it.
So in your second function, when *head = temp; is executed, you are modifying the address to which the pointer passed as argument points to.
Therefore, the author is right.
The author is correct. In your first example, you're modifying a local copy of head - the caller won't notice that anything has changed. head will still have been freed, so you're on track for a crash in pretty short order. You need to pass a pointer to modify the caller's variable.

In C++, are changes to pointers passed to a function reflected in the calling function?

If I pass a pointer P from function f1 to function f2, and modify the contents of P in f2, will these modifications be reflected in f1 automatically?
For example, if I need to delete the first node in a linked list:
void f2( Node *p)
{
Node *tmp = p;
p = p -> next;
delete tmp;
}
Will the changes made to P be reflected in the calling function, or will it now point to a memory space that has been deallocated?
( My intuitive answer here is no, changes are not reflected. However, good sources tell me that the above code will work. Can someone take the time to give the answer and explain the reasoning behind it also please? Also, if the above code is faulty, how can we achieve this without using a return type? )
If I pass a pointer P from function f1 to function f2, and modify the contents of P in f2, will these modifications be reflected in f1 automatically?
No. Since C and C++ implement pass-by-value, the value of the pointer is copied when it’s passed to the function. Only that local copy is modified, and the value is not copied back when the function is left (this would be copy-by-reference which a few languages support).
If you want the original value to be modified, you need to pass a reference to the pointer, i.e. change your signature of f2 to read:
void f2( Node*& p)
However, your f2 not only changes the pointer p, it also changes its underlying value (= the value being pointed to) by using delete. That change is indeed visible to the caller.
This will work, althrough not the way you want to.
If you call it like:
Node* mynode = new Node(); /*fill data*/
f2(mynode);
-> there will be the content of mynode undefined.
it will pass the value of the pointer to another function, and the value (p) will be local for function f2. If you want to modify it, use this way:
Node* mynode = new Node(); /*fill data*/
f2(&mynode);
void f2(Node** p)
{
Node* tmp = *p;
*p = (*p)->next;
delete tmp;
}