I am trying to create a list struct in C, where there are 3 'elements' to the struct: the content, the datatype, and the pointer to the next element in the list. Here is the code:
struct listNode{
void *content;
char datatype;
void *next;
};
typedef struct listNode listNode;
void printList(listNode *item){
while (1){
if (item->datatype == 'i'){
printf("%d\n", item->content);
} else if (item->datatype == 's'){
printf("%s\n", item->content);
} else if (item->datatype == 'c'){
printf("%c\n", item->content);
} else if (item->datatype == 'f'){
printf("%f\n", item->content);
}
fflush(stdout);
if (item->next != NULL){
item = item->next;
}
}
}
int main(){
listNode *element1;
listNode *element2;
listNode *element3;
element1->content = (char*) "Hello World";
element1->datatype = 's';
element1->next = (struct listNode *) &element2;
element2->content = (char*) 'z';
element2->datatype = 'f';
element2->next = (struct listNode *) &element3;
element3->content = (int *) 5;
element3->datatype = 'i';
element3->next = (struct listNode *) NULL;
printList(&element1);
return 0;
}
When I run the code, I get 4 warnings, and three of them are the warning I have put in as the title. Here is what happens when I compile the code:
listc.c:17:19: warning: format specifies type 'int' but the argument has
type 'void *' [-Wformat]
printf("%d\n", item->content);
~~ ^~~~~~~~~~~~~
listc.c:21:19: warning: format specifies type 'int' but the argument has
type 'void *' [-Wformat]
printf("%c\n", item->content);
~~ ^~~~~~~~~~~~~
listc.c:23:19: warning: format specifies type 'double' but the argument has
type 'void *' [-Wformat]
printf("%f\n", item->content);
~~ ^~~~~~~~~~~~~
listc.c:52:12: warning: incompatible pointer types passing 'listNode **'
(aka 'struct listNode **') to parameter of type 'listNode *' (aka
'struct listNode *'); remove & [-Wincompatible-pointer-types]
printList(&element1);
^~~~~~~~~
listc.c:14:26: note: passing argument to parameter 'item' here
void printList(listNode *item){
^
4 warnings generated.
When I run the code, I get the infamous Segmentation fault 11
. Would someone please tell me how to fix the issue and all underlying problems. Also please excuse my terrible code as this is the first time I'm working with creating my own struct. Thanks!