C++结构体指针数组
我有一个程序必须找到最短路径(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;
}
我做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在...尝试将指针分配给 int。你不能那样做。
这就是你想要
但是,当你这样做时:
你正在这样做:
做的吗?你说你想使用“结构指针数组”。您在这里传递一个指针到一个指针,并尝试存储它。
将把节点指针存储在数组中。
You're ... trying to assign a pointer to an int. You can't do that.
would need to be
However, when you do this:
you're doing this:
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.
Would be storing Node pointers in an array.
您将
pointerarray
声明为int*[]
类型。您希望它的类型为Node*[]
。You declared
pointerarray
as typeint*[]
. You want it to be typeNode*[]
.