malloc undefined
我目前正在重写链表模块,我收到一些奇怪的错误。
在两个IDE(Netbeans和Visual Studio Express)中,我收到一个警告,即malloc未定义,并且我的linkedlist.c文件中找不到的函数也没有定义。
下面是我的3个文件。
main.c中
#include #include #include "linkedlist.h" int main(void){ struct linked_list * l_list; l_list = new_list(); printf("%i", l_list->length); getchar(); return (EXIT_SUCCESS); }
linkedlist.h
#ifndef LINKEDLIST_H #define LINKEDLIST_H struct linked_list{ int length; struct linked_list_node * head_node_ptr; }; struct linked_list_node{ struct linked_list_node * prev_node_ptr; struct linked_list_node * next_node_ptr; struct linked_list_data * head_data_ptr; }; struct linked_list_data{ struct linked_list_data * prev_data_ptr; struct linked_list_data * next_data_ptr; void * data; }; struct linked_list * new_list(); #endif
linkedlist.c
#include "linkedlist.h" struct linked_list * new_list(){ struct linked_list * temp_list = malloc(sizeof(struct linked_list)); temp_list->length = 5; return temp_list; }
任何帮助将不胜感激。 我不确定这是语法问题还是我的计算机上缺少文件。
你在哪里包含
– 因为那是宣告malloc()
地方?
这是编译问题( malloc()
未声明)还是链接问题( malloc()
未定义)?
究竟是什么错误信息?
现在代码是可读的:
-
是一个C ++标头(
也是如此)。 - 您需要在C中包含
。 - 您需要在
linkedlist.c
中linkedlist.c
使用malloc()
函数的
。
你还有在linkedlist.h
错误位置的标题保护。 头文件的规范结构是:
#ifndef HEADER_H_INCLUDED #define HEADER_H_INCLUDED ...the other material in the header... ...definitions and declarations... #endif /* HEADER_H_INCLUDED */
#endif
是文件中的最后一个非注释非空行 – 而不是第三个。
即使是双向链表,您的数据结构也非常复杂。 你确定你会经常需要这么长的时间吗?它保证在列表中的每个节点都保持指向头部的指针吗? 如果你经常使用它,我会感到惊讶。 我假设您在每个节点中都有指向头的指针,这样当您从列表中删除任意节点时,您可以减少列表的长度。 你可能最好将指针传递给列表,并指向要删除的节点的指针比你得到的更好。
我在new_list()
函数new_list()
length = 5
理由。
此外,C和C ++在以下含义上有着根本的不同:
struct linked_list * new_list();
在C ++中,这意味着“ new_list()
是一个不带参数的函数,并返回一个struct linked_list
指针”。
在C中,这意味着“ new_list()
是一个具有完全不确定参数列表的函数,该列表返回struct linked_list
指针”。 该函数已声明,但该函数没有原型。
在C中,你应该写:
struct linked_list * new_list(void);
就个人而言,我更喜欢在标题中看到函数声明前面的extern
; 它实际上并不是函数所必需的,但由于它( extern
)对于在头文件中声明的变量是必需的(或者应该是),我更喜欢在头文件中声明的函数的对称性。
从您的问题来看,您似乎在Windows计算机上。 你可能必须这样做:
#include
为了让malloc()可用。
cstdlib
和cstdio
不是标准的C头。 也许你的意思是stdlib.h
和stdio.h
。
你必须使用如下的malloc()
:
for (int i = 2; i < 10; i++){ item *temp = (item*)malloc(sizeof(item)); temp->data = i; pre->next = temp; pre = temp; }