I am currently working on rewriting a linked list module and I am receiving some weird errors.
In two IDEs (Netbeans & Visual Studio Express), I am getting a war
From your question, it appears you are on a Windows machine. You may have to do:
#include <windows.h>
in order to have malloc() available.
cstdlib
and cstdio
are not standard C headers. Perhaps you meant stdlib.h
and stdio.h
.
Where do you include <stdlib.h>
— because that is where malloc()
is declared?
Is this a compilation problem (malloc()
undeclared) or a linking problem (malloc()
undefined)?
What exactly is the error message?
Now the code is readable:
<cstdlib>
is a C++ header (so is <cstdio>
).<stdlib.h>
in C.<stdlib.h>
where the malloc()
function is used — in linkedlist.c
.You also have had the header guards in the wrong place in linkedlist.h
, but the code in the question has been updated since. Originally, the sequence was:
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#endif
struct linked_list{
…
The canonical structure for a header file is:
#ifndef HEADER_H_INCLUDED
#define HEADER_H_INCLUDED
...the other material in the header...
...definitions and declarations...
#endif /* HEADER_H_INCLUDED */
The #endif
is the last non-comment, non-blank line in the file — not the third.
Your data structures are extraordinarily complicated for even a doubly-linked list. Are you sure you're going to be needing the length so often that it warrants maintaining the pointer to the head in every node in the list? I'd be surprised if you are using it that often. I assume that you have the pointer-to-head in each node so that when you remove an arbitrary node from the list you can decrement the length of the list. You'd probably be better off passing a pointer to the list and the pointer to the node to be deleted than what you've got.
I can see no justification for the length = 5
in the new_list()
function.
Also, C and C++ differ radically on the meaning of:
struct linked_list * new_list();
In C++, that means "new_list()
is a function that takes no arguments and returns a struct linked_list
pointer".
In C, that means "new_list()
is a function with a completely indeterminate argument list that returns a struct linked_list
pointer". The function is declared, but there is no prototype for the function.
In C, you should write:
struct linked_list * new_list(void);
Personally, I prefer to see extern
in front of function declarations in headers; it is not actually necessary for functions, but since it (extern
) is (or should be) necessary for variables declared in headers, I prefer the symmetry for functions declared in headers.
you must use malloc()
like below:
for (int i = 2; i < 10; i++){
item *temp = (item*)malloc(sizeof(item));
temp->data = i;
pre->next = temp;
pre = temp;
}