c - 图形程序中的结构指针数组错误

标签 c pointers graph struct

我正在尝试制作一个图表,该程序仅处于初始阶段,我 声明一个结构体指针数组,其中保存顶点地址 *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 * 类型的指针数组,我应该也给它们分配内存。

最佳答案

在主要部分:

create_vertices (&vertices);

应该是:

create_vertices (vertices);

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

更新:在 main 中,删除行:

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

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

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

关于c - 图形程序中的结构指针数组错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10773308/

相关文章:

将一阶传递函数转换为 C 代码

c - 从不兼容的指针类型赋值——如何解决?

C 使用指针比较数组元素

python - 如何在 matplotlib 中为 3D 条创建图例?

javascript - 查找父元素数据值并显示

c - 如何在C中搜索枚举类型

c - 从二进制文件更新记录(项目的一部分)(段错误)

改变字符串中的字母

c++ - 访问指针的速度

algorithm - 开发线性时间算法来遍历图