简体   繁体   中英

C++ array of pointers to structures

I have a program that has to find the shortest path (Dijkstra's algorithm), and I have decided to use an array of pointers to structures, and I keep getting this error:

In function 'void insertNode(Node**, int)' :
TDA.cpp:14: error: cannot convert 'Node**' to 'int*' in assignment

Here is my code:

struct Node{int distance, newDistance;};
int *pointerArray[20];

void insertNode(Node **n, int i)
{
    pointerArray[i] = &(*n);
}

Node *createNode(int localDistance)
{
    Node *newNode;
    newNode = new Node;
    newNode->distance = localDistance;
    newNode->newDistance = 0;

    return newNode;
}

int main()
{
    Node *n;
    int random_dist = 0;
    int i;

    for(i=0; i<20; i++)
    {
        if (i==0)
        {
            n = createNode(0);
            cout << n->distance << " distance " << i << endl;
        }
        else
        {
            random_dist = rand()%20 + 1;
            n = createNode(random_dist);
            cout << n->distance << " distance " << i << endl;
            insertNode(&n, i);
        }
    }
    return 0;
}

What am I doing wrong?

You're... trying to assign a pointer to an int. You can't do that.

int *pointerArray[20];

would need to be

Node *pointerArray[20];

However, when you do this:

pointerArray[i]=&(*n);

you're doing this:

pointerArray[i] = n;

Is that what you mean to be doing? You say you want to use an "array of pointers to structures". You're passing a pointer to a pointer here, and trying to store that.

void insertNode(Node *n,int i)
{
    pointerArray[i] = n;
}

Would be storing Node pointers in an array.

You declared pointerarray as type int*[] . You want it to be type Node*[] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM