i具有图形节点的定义节点类型:
struct node{
int data;
int neighboursNumber;
node * neighbours;
};
我正在尝试为每个节点添加一些邻居:
node * n1 = (node *)malloc(sizeof(node));
n1->data = 1;
n1->neighboursNumber = 2;
n1->neighbours = (node *)malloc(sizeof(node) * n1->neighboursNumber);
node * n2 = (node *)malloc(sizeof(node));
n2->data = 2;
n2->neighboursNumber = 1;
n2->neighbours = (node *)malloc(sizeof(node) * n2->neighboursNumber);
node * n3 = (node *)malloc(sizeof(node));
n3->data = 3;
n3->neighboursNumber = 1;
n3->neighbours = (node *)malloc(sizeof(node) * n3->neighboursNumber);
n1->neighbours[0] = n2;
n1->neighbours[1] = n3;
n2->neighbours[0] = n1;
n3->neighbours[0] = n1;
,但我在构建方面有错误
error C2679: binary '=' : no operator found which takes a right-hand operand
of type 'node *' (or there is no acceptable conversion)
这不是正确的方法吗?
而不是
struct node{
int data;
int neighboursNumber;
node * neighbours;
};
写下:
typedef struct _node{
int data;
int neighboursNumber;
struct _node * neighbours;
} node;
但是,正如其他人在评论中指出的那样,邻居应该是
struct _node ** neighbors;
(借用)我认为这对您有用...
typedef struct _node {
int data;
int neighboursNumber;
struct _node **neighbours;
} node;
int main( void ) {
node *n1 = (node *)malloc(sizeof(node));
n1->data = 1;
n1->neighboursNumber = 2;
n1->neighbours = (node **)malloc(sizeof(node *) * n1->neighboursNumber);
node * n2 = (node *)malloc(sizeof(node));
n2->data = 2;
n2->neighboursNumber = 1;
n2->neighbours = (node **)malloc(sizeof(node *) * n2->neighboursNumber);
node * n3 = (node *)malloc(sizeof(node));
n3->data = 3;
n3->neighboursNumber = 1;
n3->neighbours = (node **)malloc(sizeof(node *) * n3->neighboursNumber);
到这里...
n1->neighbours[0] = n2;
n1->neighbours[1] = n3;
n2->neighbours[0] = n1;
n3->neighbours[0] = n1;