How to retrieve pointer structure in a function - c++

I have a struct like this:
struct ClientNode
{
string name;
int flightnumber;
int clientno;
ClientNode * right;
ClientNode* left;
};
then I have declared a pointer of this struct:
ClientNode* root = new ClientNode;
in a function I have initialized clientno for root like this:
root->clientno = 11;
and then I want to send root as an argument to a function:
ClientNode newnode;
root = Insert_to_AVL_Tree(&newnode, root);
and here is my Insert_to_AVL_Tree:
ClientNode* clientclass::Insert_to_AVL_Tree(ClientNode* Node, ClientNode* root)
Here is where the error happens, I have initialized root->clientno but it seems that it changes when I pass it to another function thus it can't compare to values in the if, also node->clientno has the correct value that has been read from a file in another part of my code:
if (Node->clientno < root->clientno)
root->left = Insert_to_AVL_Tree(Node, root->left);
what is the correct way to get the root->clientno value in another function?
here is the value shown for root->clientno
here is the value for node->cleintno

For passing Pointer to functions the best way I use is double pointer
void clear(int **p)
{
*p = 0;
}
int main()
{
int* p;
clear(&p);
return 0;
}

Related

Pointers with multiple asterisk?

When declaring a pointer variable, is there ever a use for more than one asterisk? I know when you want to have a pointer point to another you would use multiple, but just to clarify, when declaring you still only put one?
Weard things: an example of 3 asterisks:
const char **stringArray;
now, if you want to allocate this array in a function as an argument, you need the following:
void stringAllocator(const char ***stringArray, int size) {
*stringArray = (const char **) malloc(size);
}
...
stringAllocator (&stringArry, 20);
...
So, you can imagine more than 3 as well, though i had never saw more than 4 :-)
an a bit weirder stuff in c++ using stars in combination with &
void stringAllocator(const char **&stringArray, int size) {
stringArray = (const char **) malloc(size);
}
...
stringAllocator (stringArry, 20);
...
In the above case works as a star reduction technique. It does the same as the first examle
When declaring a pointer variable, is there ever a use for more than one asterisk?
Sure, there are uses for declarations of pointer to pointer variables.
Let's suppose you have a function that does allocate some class instance internally, but needs to indicate failure at the same time. You can give it a signature like
bool CreateSomeType(SomeType** pointerToSomeTypePointer) {
try {
*pointerToSomeTypePointer = new SomeType();
}
catch(...) {
return false;
}
return true;
}
and being called like this
SomeType* ptr = nullptr;
if(CreateSomeType(&ptr)) {
// Use ptr
// ...
delete ptr;
}
else {
// Log failure
}
A common use case of two stars is when a function has to alter a pointer value, e.g. in ADT implementations like "Stack".
Though this design is more C than C++ (in C++ you can use other mechanisms like references), see the following example. I wrote it in "C"-style (even if you mentioned C++):
struct node {
int x;
struct node* next;
};
// this one works:
void insertBeforeHead(node** head, int value) {
struct node* newNode = (struct node*)malloc(sizeof(struct node));
newNode->next = *head;
newNode->x = value;
*head = newNode; // alters the pointer value of the caller
}
// this one does not work:
void insertBeforeHead2(node* head, int value) {
struct node* newNode = (struct node*)malloc(new Node);
newNode->next = head;
newNode->x = value;
head = newNode; // alters only the local copy of the pointer value
}
int main () {
struct node* mainHead = NULL;
insertBeforeHead(&mainHead,10); // changes the value of mainHead
insertBeforeHead2(mainHead,20); // does not change the value of mainHead, althouth it should.
}

How to manipulate the object a pointer represents C++

I am building a data structure and need to manipulate the object indicated by a pointer. The object indicated by the pointer is:
//in header file
struct treeNode{
int value;
treeNode* left;
treeNode* right;
};
My current implementation only changes what the pointer is pointing to.
target->value = oneLarger->value
Target and oneLarger are defined:
void method(treeNode* target){
treeNode* oneLarger = (tree node retrieved by another method)
target->value = more->value
}
Is this possible to do via pass by reference or do I have to pass by value?
You can do: by Pointer, by Ref, by Copy
note that changes made in the byCopy function will get lost as soon as the function is done!
Those options look like:
//by Pointer
void method(treeNode* target) {
treeNode* oneLarger = ...
target->value = oneLarger->value;
}
//by Ref
// since that is a ref, you access the value using the dot(.) and not the `->` operator
void method(treeNode& target) {
treeNode* oneLarger = ...
target.value = oneLarger->value;
}
//by Copy
// since that is a copy, you access the value using the dot(.) and not the `->` operator
void method(treeNode target) {
treeNode* oneLarger = ...
target.value = oneLarger->value;
}

C++ Binary Search Tree Insert Implementation

I'm trying to build a function to insert into a binary search tree, but I'm having a hard time figuring out why it won't work. I understand fundamentally how the function is supposed to work, but based on the template I was given it seems as though I am to avoid creating a BST class but instead rely on the Node class and build the desired functions to work on that. Here's the given template:
#include <iostream>
#include <cstddef>
using std::cout;
using std::endl;
class Node {
int value;
public:
Node* left; // left child
Node* right; // right child
Node* p; // parent
Node(int data) {
value = data;
left = NULL;
right = NULL;
p = NULL;
}
~Node() {
}
int d() {
return value;
}
void print() {
std::cout << value << std::endl;
}
};
function insert(Node *insert_node, Node *tree_root){
//Your code here
}
The issue I'm having is when I implement the following code, where getValue is a simple getter method for Node:
int main(int argc, const char * argv[]) {
Node* root = NULL;
Node* a = new Node(2);
insert(a, root);
}
void insert(Node *insert_node, Node *tree_root){
if (tree_root == NULL)
tree_root = new Node(insert_node->getValue());
The code appears to compile and run without error, but if I run another check on root after this, it returns NULL. Any idea what I'm missing here? Why is it not replacing root with a new node equal to that of insert_node?
I also realize this doesn't appear to be the optimal way to implement a BST, but I am trying to work with the template given to me. Any advice would be appreciated.
As Joachim said your issue relates to difference between passing parameter by reference and by value.
In your code void insert(Node *insert_node, Node *tree_root) you pass Node* tree_root by value. Inside the function you change local copy of this pointer, so outer value is not changed.
To fix it you should pass Node* tree_root by reference. Parameter declaration can be Node*& tree_root (or Node** tree_root). E.g:
void insert(Node* insert_node, Node*& tree_root){
if (tree_root == NULL)
tree_root = new Node(insert_node->getValue());

C++ How may I return an array class member of a nested class?

This is not a real question, since I've already solved the problem myself, but I still need some clarifications about the mechanism behind assigning an array's address to a pointer of the same type when the array is a class member of a nested class.
The following code is fully functioning, although it may lack some error_check. It is only meant to show how I made my (real) program work.
HEADER (linkedList)
class linkedList
{
public:
linkedList();
~linkedList();
int* getArray();
void forward();
private:
class listNode
{
public:
listNode();
~listNode();
friend class linkedList;
private:
int array[3];
listNode* next;
};
listNode *first;
listNode *current;
};
CPP (linkedList)
linkedList::linkedList()
{
first = new listNode;
current = first;
}
//~~~~~~~~~~~~
linkedList::~linkedList()
{
delete first;
first = 0;
current = 0;
}
//~~~~~~~~~~~~
int* linkedList::getArray()
{
if (current)
{
return &(current->array[0]);
}
}
//~~~~~~~~~~~~
void linkedList::forward()
{
if (current->next)
{
current = current->next;
}
}
//-------------------------
//-------------------------
//-------------------------
linkedList::listNode::listNode()
{
next = 0;
for (int i = 0; i < 3; i++){array[i]=((i+1)*3);}
}
//~~~~~~~~~~~~
linkedList::listNode::~listNode()
{
}
CPP (main)
#include <iostream>
#include "linked_list.h"
using namespace std;
int main()
{
linkedList list;
int *myArray;
myArray = list.getArray();
for (int i = 0; i < 3; i++){cout << myArray[i] << " ";}/**/cout << "\n\n";
return 0;
}
The real program is meant to move through a linked list made of nodes which contain 3 integer values in an array of int type, retrieve the three values and use them as parameters for some other functions.
Now, to do so I have to return the address to the first element of the array contained in the node through an accessor.
Apparently, the only way to do it is by returning the reference to the first element of the array in the node to which the linkedList's member variable current points to:
return &(current->array[0]);.
Why?
I've got to this solution through trial and error with very little knowlegde of the reasons that brought me to build this expression as it is.
Usually, when you want to assign the address of an array to a pointer, you just do so:
int main()
{
int array[3];
int* pArray;
pArray = array;
}
And that's it, because the name of the array itself is enough to retrieve the address of its first element.
The exact same result can be achieved by doing this (tested):
int main()
{
int array[3];
int* pArray;
pArray = &(array[0]);
}
Both methods are also valid when the accessor returns the address from a member variable of its own class.
But why, when accessing the member variable of a nested class, I'm forced to use the second method?
What are the logic stages that make it the only viable method?
But why, when accessing the member variable of a nested class, I'm forced to use the second method?
You aren't:
return current->array;
and
return &(current->array[0]);
Both do the same thing when the return type is int*. You aren't forced to use the second way.
Also, there's a bug in getArray. You don't return anything if current is null.
To be pedantic...
Apparently, the only way to do it is by returning the reference to the first element of the array in the node to which the linkedList's member variable current points to:
return &(current->array[0]);.
You're returning the address i.e. a pointer. Reference means something else.

c++ pointer reference confusion

struct leaf
{
int data;
leaf *l;
leaf *r;
};
struct leaf *p;
void tree::findparent(int n,int &found,leaf *&parent)
This is piece of code of BST. I want to ask. why
leaf *&parent
Why we need "reference mark" here?
parent is also a leaf, why can't I just use leaf* parent?
code below for your reference. Thank you!
void tree::findparent(int n,int &found,leaf *&parent)
{
leaf *q;
found=NO;
parent=NULL;
if(p==NULL)
return;
q=p;
while(q!=NULL)
{
if(q->data==n)
{
found=YES;
return;
}
if(q->data>n)
{
parent=q;
q=q->l;
}
else
{
parent=q;
q=q->r;
}
}
}
You are passing the pointer parent in by reference, so that you can modify that pointer:
parent=q;
If you passed the pointer in by value, the modifications would be to a copy of the pointer that expires at the end of the function.
When you use REFERENCE TO POINTER, you can change the value of the pointer. You may need to use this schema in link list implementation to change the head of the list.
void passPointer(int *variable)
{
*variable = (*variable)*2;
variable = NULL; // THIS CHANGES THE LOCAL COPY NOT THE ACTUAL POINTER
}
void passPointerReference(int* &variable)
{
*variable = (*variable)*3;
variable = NULL; // THIS CHANGES THE ACTUAL POINTER!!!!
}
int main()
{
int *pointer;
pointer = new int;
*pointer = 5;
passPointer(pointer);
cout << *pointer; // PRINTS 10
passPointerReference(pointer);
cout << *pointer; // GIVES ERROR BECAUSE VALUE OF pointer IS NOW 0.
// The constant NULL is actually the number 0.
}