Create Dynamically Allocated Array with Pointers to Structs C++ - c++

So I currently have a simple struct (linkedlist) that I will be using in a HashMap:
struct Node {
std::string key, value;
Node* head;
}
I'm currently trying to dynamically allocate an array with pointers to each struct. This is what I have right now ...
Node* nodes = new Node[100]
I understand this allocates an array of 100 nodes into memory (which I will have to delete later on); however, upon iteration to try to transverse these nodes (which I an implementing as a linked list)...
for (int x = 0; x < 100; x++) {
Node current = nodes[x]; // Problem is I wanted an array to node pointers. This is not a pointer.
while (current != nullptr) { // this isn't even legal since current is not a pointer.
// DO STUFF HERE
current = current.next; // This is not a pointer access to a method. I'm looking to access next with current->next;
}
}
Hopefully I was clear enough. Can someone how to allocate a dynamic array of pointers to structs? So far I'm able to dynamically allocate an array of structs, just not an array of pointers to structs.

There are two approaches. Either you allocate an array of structures and introduce one more pointer that will point to the element in the array that will play the role of the head.
For example
Node *head = nodes;
(in this case head points to nodes[0])
After the list will not be needed you have to delete it using operator
delete [] nodes;
Or you can indeed to allocate an array of pointers to the structure like this
Node **nodes = new Node *[100];
But in this case each element of the array in turn should be a pointer to a dynamically allocated object;
And to delete the list you at first have to delete each object pointed to by elements of the array for example in a loop
for ( int i = 0; i < 100; i++ ) delete nodes[i];
and then to delete the array itself
delete [] nodes;
It is a good idea to initialize each element of the array with zeroes when the array is allocated for example
Node **nodes = new Node *[100]();

I suggested you this structure:
class myList {
struct Node {
string value;
Node* next;
}
/*Public methods .. Add/Set/Get/Next/isEmpty.. etc ... */
Node* head, *tail;
};
in main:
myList* lis = new myList[number];
then you have number of lists! and do all work in class by method's and operators, like if you want the next node just call lis[0].getNext();
if you want to skip current node dolis[0].Next(); ... etc ..
this how to work, what you try to do is looks like C program!

Related

How to store a node in an array C++?

Isn't this a way to store a node in an array? When I try to run it I get a segmentation fault. I know that happens if you try to access memory that you do not have permission for.
In this code am I not assigning a node in an array and printing its data?
struct Node{
int data;
struct Node* next;
};
struct Node* head = NULL;
int main(){
struct Node* arr[10];
head->data = 2;
head->next = NULL;
arr[1] = head;
std::cout << arr[1]->data;
}
You are not dealing with Nodes's here, but Node pointers. They are not pointing to valid memory, unless you allocate it.
Also, don't use NULL, use nullptr instead.
head = nullptr;
head->data = 42; // this is UB, could be a segfault
If you want to do that, you have to allocate it
head = new Node{};
head->data = 42; //ok
The same logic applies for arr
arr[1] = new Node{}; // now arr[1] is pointing to valid memory
I'm not sure why you want an array of Node pointers, though. Your Node struct looks like a conventional linked-list Node, and there's a linked-list tag, so I'm guessing you want to implement linked-lists.
In that case, you don't need an array of Node pointers at all. The entire linked-list should be connected through the head.
If you just want an array of Nodes, then you can do that, and not worry about memory allocation at all.
Node arr[10] {};
arr[1].data = 42; // ok

C++ trying to delete Binary Tree and move it to Vector

So I'm trying to write a function that places all of the values of a binary tree into a vector, which will later be used to recreate it. But when I try to call this function, I get an error:
Error in `./bst': double free or corruption (fasttop):
This is the function I'm using. The vector itself is a private variable containing nodes. size() returns the size of the tree and is working.
void BST::swapvector()
{
Node *ptr = m_root;
while (size() != 0)
{
if (ptr->m_left != NULL) {
ptr = ptr->m_left;
} else if (ptr->m_right != NULL) {
ptr = ptr->m_right;
} else {
Node *temp = ptr;
myvector.push_back(ptr); //starting from root, we traverse until we reach the bottom and then add ptr to the vector
ptr = m_root;
delete temp; //once we're finished, we delete temp
}
}
}
Does anyone know why this isn't working? Thanks!
It's obvious why this isn't working.
} else {
Node *temp = ptr;
myvector.push_back(ptr); //starting from root, we traverse until we reach the bottom and then add ptr to the vector
ptr = m_root;
delete temp; //once we're finished, we delete temp
}
You're storing a pointer to Node into vector and then deleting that Node with delete temp. After that pointer stored into vector points to garbage or non-existent memory.
"...a function that places all of the values of a binary tree into a vector..."
No, you're not storing binary tree values, you're storing pointers to binary tree values (Node objects).
There are two things you can do:
If the binary tree will not be freed nor changed for the lifetime of myvector then you can just remove the delete temp; line.
If assumption in the first case is not true, then you need to store Node elements into vector, not pointers to them. So, define myvector as vector<Node> myvector; instead of vector<Node *> myvector; and change myvector.push_back(ptr); to myvector.push_back(*ptr);.
You cannot delete temp after you place it a vector. Also, how is your vector defined? There might be problem there.
Also you should use iterators instead of push_back() function. It doesn't work well with pointers.
And, why does everyone insist on using c-style pointers. Use shared or unique pointers. Please?
Type of error usually signifies that a pointer being freed twice.

how to create a array of pointers

I'm trying to create an array of pointers for my hashtable. But I'm having trouble because I keep on getting segmentation faults for my functions(i.e. add, remove, find, delete functions) and I'm not sure if it's because I don't have my array of pointers declared and defined correctly. Here is what I have:
Node **array = new Node* is this how you would create a dynamic array of pointers?
I think you can use :
Node **array = new Node*[10];
setting the pointer :
Node node;
array[0] = &node;
and remember to delete :
delete[] array;

C++ Is it possible to leak memory if i'm not using dynamic memory

None of my code uses dynamic memory, but I do have a vector of pointers to a struct called Node, and in my code, I do lose references to those Nodes at one point. The struct looks like this:
struct Node {
int value;
Node* next;
};
I also have a for loop that tries to find the smallest value in my vector of Node pointers by taking the smallest Node off as I go. Here, lists is the vector of Node pointers, and add is the previous smallest value.
for (int i = 1; i < int(lists.size()); ++i) {
if (lists[i]->value <= add) {
add = lists[i]->value;
lists[i] = lists[i]->next;
break;
}
}
I thought I couldn't leak memory if I was just in the stack though...
If the Node referenced in the lists array is dynamically allocated, you should free all of them manually. Otherwise there will be memory leak. You can find more details on https://en.wikipedia.org/wiki/Memory_leak

C++ struct - pointer to pointer and dynamic array

I want to implement a tree trie and insert an example value into the key variable I am using a pointer to pointer and creating a dynamic array of 100 elements but my application crashes after starting.
#include<iostream>
using namespace std;
struct node {
int key;
node **children;
};
int main() {
node *child;
child = new node;
child->children = new node *[100];
child->children[20]->key = 90;
cout<<child->children[20]->key;
return 0;
}
You need to allocate memory for child->children[20]. You allocated memory for child->children but not for the elements in the array. You can do this as follows:
for (int i=0;i<100;++i) {
child->children[i] = new node;
}
By storing a node * you are storing the address of a node which contains the address of an array of addresses of nodes. This means that you need to allocated memory for all three levels of the hierarchy. You only allocated memory for two of the layers.