C++结构体指针数组

3

我有一个程序需要找到最短路径(Dijkstra算法),我决定使用指向结构体的指针数组,但是我一直收到如下错误:

在函数 ‘void insertNode(Node**, int)’ 中:
TDA.cpp:14: 错误:无法将赋值中的 ‘Node**’ 转换为 ‘int*’

这是我的代码:

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;
}

我做错了什么?

2个回答

3

您正在尝试将指针分配给整数。这是不允许的。

int *pointerArray[20];

需要成为
Node *pointerArray[20];

然而,当您执行以下操作时:
pointerArray[i]=&(*n);

你正在做这件事:

pointerArray[i] = n;

您的意思是要使用“指向结构体的指针数组”吗?但是您在这里传递了一个指向指针的指针,并试图进行存储。

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

将会在一个数组中存储Node指针。


1
你声明了一个类型为 int*[]pointerarray 。 你想让它成为类型 Node*[]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接