Pointer to a Struct/ Class within the struct/class C++ - c++

Hi I am from a Java background and quite new to C++
In my intermediate level of Java programming i never had situation where i declared an object of some
class within the body of that class, now am studying linked lists in C++, here in this code and in several
other places i have come across that pointer to that class/struct is declared within its body i.e Struct ListNode * next; in the following code
private:
// Declare a structure for the list
structListNode{
float value;
structListNode*next;
};
ListNode*head; // List head pointer
public:
FloatList(void) { // Constructor
head = NULL;
}
~FloatList(void) { }; // Destructor
void appendNode(float);
void displayList(void);
void deleteNode(float);
};
or Node * next ; in this code below
class Node {
int data; // The value stored in node
Node* next; // The address of next node
}
I can'really comprehend what it means or how is it going , can someone please explain it to me?

The pointer inside struct/class is not an "object" of that struct/class, instead, it is a pointer of the objects of the same type. It just stores/holds address of objects created somewhere else, so it can access or modify them without copying their content.
As an example;
class Node {
int data;
Node* next;
};
int main(){
Node* head = NULL; // This is a pointer, not an object.
// It points to NULL (i.e. nothing) yet.
Node n1, n2; // These two are "objects" of Node class
head = &n1; // head now points to n1, i.e. holds memory address of n1
n1.data = 10; // n1.data contains 10
n1.next = &n2; // n1.next points to the object n2
n2.data = 20; // n2.data contains 20
n2.next = NULL; // n2.next points to nothing
head->data = 5; // now, n1.data contains 5, instead of 10
head->next->data = 15; // now, n2.data contains 15, instead of 20
return 0;
}

Related

Nested linked list in C++

I'm trying to build a nested linked list in C++ (pretty new to C++).
The node in the list could be an integer value or another linked list that has all integer values.
I have gone through other posts on SO, and I understand I should use a union for multiple data types for the node data type.
This is what I have until now.
class linkedList {
private:
struct node {
union data {
int val;
linkedList* list;
};
data currData;
node* next; // a pointer which will point to the next node
}*p;
My question is how do I start allocating the list pointer within the node struct.
For val, I know I can do p->currData->val =5, for example.
I wouldn't use a union. I would just keep a value for each and a typefield of some sort so you know what it is.
class LinkedList {
public:
class Node {
LinkedList * list = nulptr;
int value = 0;
Node * next = nullptr;
};
};
In this case, if list is nullptr, then it's not a node pointing to a new list. Or you could explicitly add a type, but for something this simple, I probably wouldn't.
p->value = 5;

HOW ARE Node a and Node* s different?

struct Node
{
int w;
Node* w1;
};
int main(){
Node a;
Node *s;
}
In above code what is difference between a and *s. How are they different.Also why we use Node *s while creating a LinkList.
THANK YOU!!!
Node a is an object. It allocates some space in memory.
Node *s1 - is pointer to object of type Node, but the object itself must be created with, for example, a new operator. Or we must explicitly take and address of the object with & operator. It is just a variable that holds an address. The size of this variable depends on platform (4 bytes on x86, 8 bytes on x86_64).
Each node of a Linked list stores a pointer to the next node. That is why we need a pointer here. Thus if you you have access to the node, you can travel to the next and to the end of the list.
Disclaimer: The given code is very basic and given for explanation only. This is not how you create linked list in real-life. Manually connecting nodes is not a great pattern. I would recommend you to learn more about basic language concepts like pointers, references, object lifetime.
// Node type definition
struct Node
{
int w;
Node* w1;
};
int main() {
// Separate nodes
Node n1;
Node n2;
Node n3;
// Now this is a linked list
n1.w1 = &n2;
n2.w1 = &n3;
n3.w1 = nullptr; // to mark the end
// Get pointer to n2 from n1
Node *n2_ptr = n1.w1;
Node *n3_ptr = n2.w1;
// Check if n3 is the last element
if (n3_ptr->w1 == nullptr) {
// this is the end of the list
}
// walk the list
Node *node = &n1;
while (node != nullptr) {
node->w *= 2; // do smth with data
node = node->w1; // go to the next node
}
return 0;
}

C++ pointer to class object [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Passing pointer to local variable to function: is it safe?
(6 answers)
Closed 3 years ago.
I encounter a strange issue when using class in C++.
Here is my code to add object the my linked list. I found that my V1 code works correct but V2 code doesn't and the printList can never stop in V2. Do anyone can explain why it is the case, since I expect V1 and V2 code should output the same outcome.
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
Node() {
cout << "Node object is being created" << endl;
}
};
void printList(Node *node) {
while(node != NULL) {
cout << node->data << ",";
node = node->next;
}
cout << endl;
}
void push(Node **node, int data) {
// // working V1 start
// Node *newNode = new Node();
// newNode->data = data;
// newNode->next = *node;
// *node = newNode;
// // working V1 end
// not working V2 start
Node newNode;
newNode.data = data;
newNode.next = *node;
*node = &newNode;
// not working V2 end
}
int main() {
Node *a = NULL;
push(&a, 15);
push(&a, 10);
printList(a);
}
Your V2 stores a pointer to a node in automatic storage. That node is automatically destroyed at the end of the push function at which point the pointer is left dangling and no longer points to a valid object.
When you later attempt to indirect through that pointer, the behaviour of the program is undefined.
V1 does not have this problem, since it allocates the nodes in dynamic storage. Instead, the problem with V1 is that it leaks the allocated memory. Dynamic allocations created with new-expression need to be deallocated with delete-expression.
The second code snippet has undefined behaviour because 1) the pointer newNode is not initialized and 2) you did not allocate memory where you are going to store values data and *node.
Node newNode;
newNode.data = data;
newNode.next = *node;
In the first code snippet a memory for the new node is allocated and the pointer is initialized by the address of the allocated memory
Node *newNode = new Node();
So these statements
newNode.data = data;
newNode.next = *node;
are valid and write data to the allocated memory.
Take into account that if to define the class the following way (removing the default constructor)
class Node {
public:
int data;
Node *next;
};
then the function can be written much simpler
void push( Node **node, int data )
{
*node = new Node { data, *node };
}

Getting wrong output with custom linked list implementation

I am learning list in C++ independently, and i have searched many websites about it. However, almost every approach to create a list is the same.
They usually create a struct as the node of a class. I want to create a class without using struct. So I created a class name ListNode which contains an int data and a pointer.
The main member functions of my class are AddNode and show.
Although, this program compiles successfully, it still does not work as I wish.
Here is the header file:
#ifndef LISTNODE_H_
#define LISTNODE_H_
#pragma once
class ListNode
{
private:
int data;
ListNode * next;
public:
ListNode();
ListNode(int value);
~ListNode();
void AddNode(ListNode* node,ListNode* headNode);
void show(ListNode* headNode);
};
#endif
Here is the implementation:
#include "ListNode.h"
#include<iostream>
ListNode::ListNode()
{
data = 0;
next = NULL;
}
ListNode::ListNode(int value)
{
data = value;
next = NULL;
}
ListNode::~ListNode()
{
}
void ListNode::AddNode(ListNode* node,ListNode* headNode) {
node->next = headNode;
headNode =node;
}
void ListNode::show(ListNode* headNode) {
ListNode * traversNode;
traversNode = headNode;
while (traversNode != NULL) {
std::cout << traversNode->data << std::endl;
traversNode = traversNode->next;
}
}
Main function:
#include"ListNode.h"
#include<iostream>
int main()
{
using std::cout;
using std::endl;
ListNode* head = new ListNode();
for (int i = 0;i < 3;i++) {
ListNode* Node = new ListNode(i);
head->AddNode(Node, head);
}
head->show(head);
return 0;
}
As far as I am concerned, the output should be
2
1
0
However, the output is a single zero. There must be something wrong in the AddNode and show function.
Could you please tell me what is wrong with these two functions?
When you call head->AddNode(node, head) you´re passing the memory directions which the pointers point, when the function arguments receive those directions, they are now pointing to the same directions, but those are another pointers, no the ones you declared in main. You could see it like this:
void ListNode::AddNode(ListNode* node,ListNode* headNode) {
/*when the arguments get their value it could be seen as something like:
node = Node(the one from main)
headNode = head(the one from main)*/
node->next = headNode;
/*Here you are modifying the new inserted node, no problem*/
headNode = node;
/*The problem is here, you´re modifying the memory direction
headNode points to, but the headNode argument of the function, no the one declared in main*/
}
So the pointer head in main() always points to the same first node you also declared in main().
In order to fix this you should change your code this way:
void ListNode::AddNode(ListNode* node,ListNode** headNode) {
/* second paramater now receives a pointer to apointer to a node */
node->next = *headNode;//the same as before but due to pointer syntaxis changes a bit
*headNode = node;//now you change the real head
}
And when you call it:
head->AddNode(Node, &head);//you use '&' before head
Now the real head, no the one in the function, will point to the last node you inserted.

C++ bad PTR in char* (Expression cannot be evaluated)

I've been searching for quite a time for an answer, although there were similar problems I still couldn't improve my code so it would work.
I have a simple lifo structure to which I am trying to add one element and print the structure. It prints nothing and when I am debbuging I have this <bad ptr> in char * nameOfVariable.
I would appreciate any help! Here is my source code:
#include<stdio.h>
struct Variable
{
double value;
char *name;
struct Variable *next;
} *variables[80000];
void pop(Variable * head);
void push(Variable * head, char *name, double value);
void show(Variable * head);
int main(){
for(int i = 0; i <80000; i++){
variables[i] = nullptr;
}
char *nameOfVariable = "aaab";
double value = 5;
push(variables[0], nameOfVariable, value );
show(variables[0]);
system("pause");
return 0;
}
void push(Variable * head, char *name, double value)
{
Variable * p ;
p = head;
head = new Variable;
head -> name = name;
head -> value = value;
head -> next = p;
}
void pop(Variable * head)
{
Variable *p;
if (head != NULL)
{
p = head;
head = head -> next;
free(p);
}
}
void show(Variable * head)
{
Variable *p;
p = head;
while (p!=NULL){
printf("%c %f ", p->name, p->value);
p=p->next;
}
printf("\n");
}
PS - I cant use STL so string is not an option :)
You are storing a pointer into a parameter location:
void push(Variable * head, char *name, double value)
{
Variable * p ;
p = head;
head = new Variable;
But the parameter location is local to the function and discarded upon return.
Why do you allocate an array of 80000 elements?
In order to change a location by a function you must either pass the address of that location (a Variable** head in your case) or use a reference.
Much better would be the definition of a class for your stack...
And another one: storing a variable's name as a char* will almost certainly cause trouble later on. Prepare for memory allocation of a char[] and copy the name string.
You do not save the variable you created in push so they all get lost
void push(Variable * head, char *name, double value) {
Variable * p ;
p = head;
head = new Variable;
head -> name = name;
head -> value = value;
head -> next = p;
}
When the function enters head points to null.
in head = new Variable; head now points to a newly created variable on the heap
when the function exits no one keeps track of the newly created variable on the heap. The memory is leaked and there is no way to access that element.
NOTE: You should be aware that Changes you write to head in the function push do not affect variables[0] you passed to the function. variables[0] is pointer to a Variable somewhere. Initially it is nullptr meaning it does not point at anything. head is a copy of variables[0] that means a different pointer that happens to point at the same place in memory (in your case nullptr). That means though that if you change head it points at something else and is no longer pointing to the same object as variables[0]
Suggested Changes:
Make push a function that returns a Variable* to the caller. Which is the new head.
Make push a function that accepts a Variable*& as an in/out parameter and returns the new head in that
(My preference) create a deque struct that holds a Variable* head memeber. pass a deque* to all these functions (push/pop) and in these functions manage the memory