我正在尝试使用邻接表来实现图形,据我所知,如果我创建变量 array
指向 struct adjlistnode
的大小 >v*sizeof(struct adjlistnode)
thin i可以在数组的每个索引中存储v struct adjlistnode
类型节点的地址
意味着数组的每个索引都将指向 struct adjlistnode
类型的节点,但是当我分配 G->array[i]=NULL
时,它给我错误
||=== 构建:在 teeest 中调试(编译器:GNU GCC 编译器)===|
C:\Users\Mahi\Desktop\DATA STR\teeest\main.c||在函数“creategraph”中:|
C:\Users\Mahi\Desktop\DATA STR\teeest\main.c|59|错误:从类型“void *”分配到类型“struct adjlistnode”时类型不兼容|
||=== 构建失败:1 个错误,0 个警告(0 分钟,0 秒)===|
why i am not able to assign NULL to index of array
如果我想访问邻接表,比如使用G->array[i]
=first node address adjacent to i
th vertex of graph and later,我应该怎么做如果需要我会添加另一个节点
struct adjlistnode{
int dest;
struct adjlistnode* next;
};
struct graph{
int V;
struct adjlistnode* array;
};
struct adjlistnode* getnewnode(int dest){
struct adjlistnode* newnode =(struct adjlistnode*)malloc(sizeof(struct adjlistnode));
newnode->dest=dest;
newnode->next=NULL;
return newnode;
}
struct graph* creategraph(int v){
struct graph* G=(struct graph*)malloc(sizeof(struct graph));
G->V=v;
G->array=(struct adjlistnode*)malloc(v*sizeof(struct adjlistnode));
for(int i=0;i<v;i++){
G->array[i] =NULL;
}
return G;
}
最佳答案
G->array
的类型是 struct adjlistnode *
但是
G->array[i]
是 struct adjlistnode
类型。
因此,您不能将 NULL
(类型为 void *
)分配给类型为 struct adjlistnode 的
G->array[i]
您可能必须将 struct graph
中的 array
定义为pointer to pointer
struct graph{
int V;
struct adjlistnode** array;
};
然后下面的应该对你有用
struct graph* creategraph(int v){
struct graph* G=malloc(sizeof(struct graph));
G->V=v;
G->array=malloc(v*sizeof(struct adjlistnode*));
for(int i=0;i<v;i++){
G->array[i] =NULL;
}
return G;
}
** 注意 1(@alk 在评论中也提到)在 C 中,至少从 C89 标准开始,malloc
返回 void *
。 void *
可以分配给任何其他指针类型(反之亦然),因此不需要转换 malloc
的返回值。
** Note2(@alk 也指出)malloc
签名是用 size_t
类型的参数定义的,而不是 int
所以最好稍微修改一下代码并使用正确的类型(阅读 comparing int with size_t 和 size_t vs int in C++ and/or C 了解更多信息)
关于c - 数组不存储结构的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52536202/