简体   繁体   中英

C Programming Compile Issue

Hey guys I am preparing for a interview where most of the programming will be done in C. I decided to implement a Linked List class in C so as to understand how objects are really implemented in a lower level language that does not support an object oriented paradigm. I have run into some compile issues, so anyone who is familiar with C please help (I have never programmed in C). I have posted my code below as well as the compile error immediately after it.

//Creating a LinkedList in C
//with 3 basic operations
#include <stdio.h>
typedef struct node {
   int data;
   node* next;
} List;

void insertEnd(List *node, int elem);
void PrintList(List *node);
/*void insertEnd(List *node, int elem);
void remove(List *node, int elem);*/

int main () {
    List *head = (List *)malloc(sizeof(List));
    head->data = 0;
    head->next = NULL;
    insertEnd(head, 3);
    insertEnd(head, 4);
    PrintList(head);
}
void insertEnd(List *node, int elem) {
    while (node->next != NULL) {
        node = node->next;
    }
    List *new_node = (List *)malloc(sizeof(List));
    new_node->data = elem;
    new_node->next = NULL;
    node->next = new_node;
}

void PrintList(List *node) {
while (node) {
    printf ("%i ->", node->data);
    node = node->next;
}
}

The error is as follows:

bash-4.1$ gcc -o LinkedList LinkedList.c
LinkedList.c:6: error: expected specifier-qualifier-list before ‘node’
LinkedList.c: In function ‘main’:
LinkedList.c:15: warning: incompatible implicit declaration of built-in function ‘malloc’
LinkedList.c:17: error: ‘List’ has no member named ‘next’
LinkedList.c: In function ‘insertEnd’:
LinkedList.c:24: error: ‘List’ has no member named ‘next’
LinkedList.c:25: error: ‘List’ has no member named ‘next’
LinkedList.c:27: warning: incompatible implicit declaration of built-in function ‘malloc’
LinkedList.c:29: error: ‘List’ has no member named ‘next’
LinkedList.c:30: error: ‘List’ has no member named ‘next’
LinkedList.c: In function ‘PrintList’:
LinkedList.c:36: error: ‘List’ has no member named ‘next’

The member next should be declared with struct node *next and you have to include stdlib.h which contains the declaration of malloc :

And you have to compile with -Wall flag until your program is free from bugs.

#include <stdlib.h>

// ...

typedef struct node {
   int data;
   struct node *next;
} List;

// ...

change

typedef struct node {
   int data;
   node* next;
} List;

to

typedef struct node {
   int data;
   struct node* next;
} List;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM