Array that holds pointers

closed account (NCRLwA7f)
This question has been asked plenty of time, yet for some reason, I cannot get it to work despite how many resources I read. I'm actually working on a hash stable and want to be able to use an array that holds linked list in each Array "slot" I want to be able to go to myArray[i] and read the address to jump to that linked list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
using namespace std;

struct node{
	int key;
	node* pNext;
};



int main() {
	
	int** myArray;
	
	myArray = new int*[5];

        for(int i = 0; i < 5; i++)
	   myArray[i] = nullptr;
	
	node* myNode = new node();
	myNode->key = 45;
	myNode->pNext = nullptr;

        myArray[0] = myNode; //Assigning to 'int *' from incompatible type 'node *'
	myArray[0] = &myNode; //Assigning to 'int *' from incompatible type 'node **' 
	  

return 0;


this is just a little sample of what I'm trying to do, I'm just trying to get it working 1st before getting any actual use out of it.
myarray[0] appears to be an integer pointer:
myArray = new int*[5];

mynode appears to be a node pointer:
node* myNode = new node();

this is not legal (you can force fit it with casting, though). Lets not do that. The compiler knows the two are not the same type of pointer, and is not allowing this without force, and force here is probably bad.

you probably want this:

node** myArray;
myArray = new node*[5];

...
myarray[0] = mynode; //ok, same type of pointer now.


closed account (NCRLwA7f)
ok, that appears to work out.

I did notice that now if I do myArray[0]->key or myArray[0]->pNext I can access the values from the node. Would I use this like I would normaly use a node?
1
2
3
4
5
 
node* temp = new node(); 
temp->key;
temp->pNext;
   
there are a number of identical or nearly identical ways to access pointers that look different but do the same thing. Use whichever syntax you prefer. The compiler will tell you if you mangle it.

You can mix ->, *, [], addition, and probably some others as well to do the exact same thing.

I would have done

myarray[index][otherindex].key = value;

I don't like * notation *myarray style as it is confusing writing math, which is what I did mostly.
I don't like -> as it is unable to work with blocks of memory (a pointer that represents an array)
I don't like math because it quickly becomes unclear what the person is doing. The most Ill do there is ++ a pointer in a loop, rarely.

that leaves [], which is fairly explicit, handles blocks, and worked for me :)

Just remember to delete [] myArray; when you're done, which should call the destructor on each of its elements. Or design the whole thing with vectors.
Topic archived. No new replies allowed.