-1

我正在尝试制作一个图表,该程序正处于初始阶段,我声明了一个结构指针数组,其中包含顶点地址 *vertices[20] 是一个数组,其元素都是 struct node *类型的地址,它将包含图节点的地址。

#include<stdio.h>
#include<stdlib.h>
struct node {
    int data;
    struct node *links[10];
};
struct node *create_node(int);
void create_vertices(struct node **);
int main()
{
    struct node *vertices[20];
    int d, i, choice;
        *vertices[0]=(struct node *)malloc(sizeof(struct node)*20);
        create_vertices (&vertices);
}

struct node *create_node(int data)
{
    int i;
    struct node *temp = (struct node *)malloc(sizeof(struct node));
    temp->data = data;
    for (i = 0; i < 10; i++)
        temp->links[i] = NULL;
    return temp;
}

void create_vertices (struct node **v)
{
 int i,choice;
 i=0;
    printf("enter choice\n");
    scanf("%d", &choice);
    while (choice == 1) {
        printf("enter data\n");
        scanf("%d", &d);
        vertices[i] = create_node(d);
        i++;
        printf("enter choice\n");
        scanf("%d", &choice);
    }
}

编译上面的代码会给我以下错误

bfs.c: In function ‘main’:
bfs.c:13:21: error: incompatible types when assigning to type ‘struct node’ from type ‘struct node *’
bfs.c:14:9: warning: passing argument 1 of ‘create_vertices’ from incompatible pointer type [enabled by default]
bfs.c:8:6: note: expected ‘struct node **’ but argument is of type ‘struct node * (*)[20]’
bfs.c: In function ‘create_vertices’:
bfs.c:35:16: error: ‘d’ undeclared (first use in this function)
bfs.c:35:16: note: each undeclared identifier is reported only once for each function it appears in
bfs.c:36:3: error: ‘vertices’ undeclared (first use in this function)

该程序在以下行中显示错误

    struct node *vertices[20];
*vertices[0]=(struct node *)malloc(sizeof(struct node)*20);

这种声明有什么害处。我声明了一个 struct node * 类型的指针数组,我应该也给它们内存。

4

1 回答 1

0

主要:

create_vertices (&vertices);

应该:

create_vertices (vertices);

另外:让 create_vertices() 函数知道数组的大小会更安全。不应允许 i 索引超过此大小。

更新:主要,删除行:

*vertices[0]=(struct node *)malloc(sizeof(struct node)*20);

Vertices[] 是自动存储(“在堆栈上”)中的 20 个(未初始化的)指针数组。

create_vertices() 函数会给指针一个值。(通过调用 malloc() 并将结果分配给 vertices[i])

于 2012-05-27T10:41:06.980 回答