开发者

C++ array of pointers to structures

开发者 https://www.devze.com 2023-03-02 16:27 出处:网络
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:

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)’开发者_如何学Go:

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*[].

0

精彩评论

暂无评论...
验证码 换一张
取 消