2
votes

list.h

#ifndef LIST_H
#define LIST_H

/* Function prototypes */
struct nodeStruct* List_createNode(int item);
#endif

list.c

#include <stdio.h>
#include <stdlib.h>

struct nodeStruct {
    int item;
    struct nodeStruct *next;
};
struct nodeStruct* List_createNode(int item) {
    struct nodeStruct *node = malloc(sizeof(struct nodeStruct));
    if (node == NULL) {return NULL;}
    node->item = item;
    node->next = NULL;
    return node;
}

Main.c:

#include "list.h"
#include <assert.h>
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

struct nodeStruct *one = List_createNode(1);
while(one != NULL) {
    printf("%d", one->item); //error
    one= one->next; //error
}

Error: error: dereferencing pointer to incomplete type printf("%d", one->item); The error is at one->item, I have tried several combinations to dereference, but does not seem to work. What's the right approach?

Updated:

list.h

#ifndef LIST_H
#define LIST_H

    struct nodeStruct {
    int item;
    struct nodeStruct *next;
};
/* Function prototypes */
struct nodeStruct* List_createNode(int item);
#endif

Now the error is, invalid application of ‘sizeof’ to incomplete type ‘struct nodeStruct’ struct nodeStruct *node = malloc(sizeof(struct nodeStruct)); From my list.c file.

2
Did you include the definition of struct nodeStruct in the main .c file? Also, you probably want to remove the * in one = *one->next;. Oh, and modifying one may leak memory. - EOF
@EOF that's not the problem because other methods work. - Aaron
So the definition of struct nodeStruct is, in fact, not available to main(). Put the definition of struct nodeStruct into list.h. Hint: It's currently in list.c. - EOF
...And now you also need to #include "list.h" in list.c. - EOF
Actually, where's your int main() function? It's not in the main.c you've posted - EOF

2 Answers

2
votes

I can think of couple of ways:

  1. Put the definition of struct in a header file and #include the header file in main.c.

  2. Add couple of functions

    int getNodeItem(struct nodeStruct* node)
    {
       return node->item;
    }
    
    struct nodeStruct* getNextNode(struct nodeStruct* node)
    {
       return node->next;
    }
    

    and call the functions from main.

    while (one != NULL) {
       printf("%d", getNodeItem(one));
       one = getNextNode(one);
    }
    
0
votes

Add #include "list.h" in list.c. When gcc tries to compile the latter, the local invocation of the compiler doesn't know about the struct nodeStruct because its definition has not been included in the local file.

Note: this is based on your update in which struct nodeStruct is defined in list.h.