gpt4 book ai didi

c - 警告不兼容的指针,为什么会发生这种情况?

转载 作者:行者123 更新时间:2023-12-02 03:24:28 25 4
gpt4 key购买 nike

#include <stdio.h>
typedef int element_type;

typedef struct Cell{
element_type e;
struct Cell *next;
} Cell,*List;

Cell *End(List L){
Cell *q = L;
while (q->next != NULL){
q = q->next;
}
return q;
}

void Insert(Cell *p, element_type x){
//Create new Cell
Cell *temp = (Cell*) malloc(sizeof(Cell));
if (temp == NULL){
printf("Memory Allocation Failed");
}
else{
temp->e = x;
temp->next = p->next;
p->next = temp;
}
}

element_type Retrieve(Cell *p){
return p->e;
}
int main(){
//Initialize the List;
List L = malloc(sizeof(Cell));
L->e = NULL;
L->next = NULL;

element_type x = 10;
Insert(L,x);
printf("Just retrievd the item %d\n",Retrieve(L));
return 1;
}

List_pointer.c: In function ‘Insert’:
List_pointer.c:19:24: warning: incompatible implicit declaration of built-in function ‘malloc’ [enabled by default]
List_pointer.c: In function ‘main’:
List_pointer.c:35:12: warning: incompatible implicit declaration of built-in function ‘malloc’ [enabled by default]
List_pointer.c:36:8: warning: assignment makes integer from pointer without a cast [enabled by default]

感谢您的所有帮助,感谢我现在的结构部分。但是,当我尝试使用 malloc 时,我再次收到有关不兼容声明的警告。我认为 malloc 返回一个指向 NULL 的通用指针,因此转换应该不会有任何问题?我只是不确定我在这里做错了什么。

对于那些想知道为什么我会实现如此奇怪的接口(interface)的人,我正在遵循 Aho 的《数据结构和算法》一书提供的接口(interface)。示例代码是用 Pascal 语言给出的,相当旧的风格。虽然我认为学习这种超古老的数据结构设计方法有一些优点。

更新:

我只是忘记包含 malloc 的 stdlib.h header !请引用此链接incompatible implicit declaration of built-in function ‘malloc’

最佳答案

你需要改变

typedef struct {

typedef struct Cell {

typedef struct {/* ... */} Cell; 定义一个无标签结构。实际上,结构本身没有可以直接引用的名称。名称 Cell 只是引用此未命名结构的 typedef 的名称。

当您使用struct Cell声明next时,它的意思是“名为Cell的结构”。但是,没有名为 Cell 的结构,因为您定义的结构没有名称。

通过命名结构(为其指定标签),您可以使用 struct Cell 表示法引用它。

关于c - 警告不兼容的指针,为什么会发生这种情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11595627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com