C 指向函数返回的指针。从不兼容的指针类型初始化
我的指针有些问题。我有一个函数,它应该返回链表中的节点,该函数应该返回指向变量的指针。我很困惑,看不出我做错了什么 data.h-头文件C 指向函数返回的指针。从不兼容的指针类型初始化,c,pointers,C,Pointers,我的指针有些问题。我有一个函数,它应该返回链表中的节点,该函数应该返回指向变量的指针。我很困惑,看不出我做错了什么 data.h-头文件 int add(int num); struct message *findMessage(int num); typedef struct list_el message; c-链表 #include <stdio.h> #include <stdlib.h> struct list_el { int num;
int add(int num);
struct message *findMessage(int num);
typedef struct list_el message;
c-链表
#include <stdio.h>
#include <stdlib.h>
struct list_el {
int num;
struct list_el *next;
};
typedef struct list_el message;
struct list_el *head, *tail;
int addNode(struct list_el *curr)
{
if(head == NULL) {
head = curr;
} else {
tail->next = curr;
}
curr->next = NULL;
return 0;
}
int add(int num)
{
message *curr;
head = NULL;
curr = (message*) malloc(sizeof(message));
curr->num = num;
addNode(curr);
return 0;
}
message *findMessage(int num)
{
message *curr;
for(curr = head; curr != NULL; curr = curr->next) {
if(curr->num == num) {
return curr;
}
}
return NULL;
}
#包括
#包括
结构列表{
int-num;
结构列表_el*下一步;
};
类型定义结构列表消息;
结构列表头、尾;
int addNode(结构列表\u el*curr)
{
if(head==NULL){
水头=电流;
}否则{
尾部->下一步=当前;
}
当前->下一步=空;
返回0;
}
整数加(整数)
{
信息*货币;
head=NULL;
curr=(message*)malloc(sizeof(message));
curr->num=num;
addNode(curr);
返回0;
}
message*findMessage(整数)
{
信息*货币;
for(curr=head;curr!=NULL;curr=curr->next){
如果(当前->数值==数值){
返回货币;
}
}
返回NULL;
}
Main.c-Main
#include <stdio.h>
#include "data.h"
int main(void)
{
int num = 2;
add(num);
message *curr = findMessage(num);
return 0;
}
#包括
#包括“data.h”
内部主(空)
{
int num=2;
添加(num);
message*curr=findMessage(num);
返回0;
}
为什么不在标题中包含结构列表的定义?否则,main
无法使用它。为什么不将结构列表的定义包含在标题中?否则,main
将无法使用它。这与我使用的typedef不一样吗?@user:No,标题必须包含实际的结构声明。否则任何外部代码都将无法使用它:-)这与我使用的typedef不一样吗?@user:No,头必须包含实际的结构声明。否则,任何外部代码都无法使用它:-)您实际上没有在add/addNode中分配新节点-您需要调用malloc来分配storage.Hi。对不起,我只是把它作为一个例子编码进来。现在已更正,但指针问题尚未修复。@user265767:nope-上面发布的代码仍然不完整-您没有分配任何节点。与问题无关,但tail->prev=tail
将尾部节点链接到自身毫无意义。仍然存在许多简单/明显的错误-请尝试在调试程序中单步执行代码-实际上,您没有在add/addNode中分配新节点-您需要调用malloc来分配storage.Hi。对不起,我只是把它作为一个例子编码进来。现在已更正,但指针问题尚未修复。@user265767:nope-上面发布的代码仍然不完整-您没有分配任何节点。与问题无关,但tail->prev=tail代码>将尾部节点链接到自身毫无意义。许多简单/明显的错误仍然存在-请尝试在调试器中单步执行代码