-2

I'm trying to define a function that will return a pointer to a structure. I think I followed this correctly, (Returning a struct pointer) but my code keeps complaining with this error message when I try to access the pointer's members, "error: dereferencing pointer to incomplete types".

Here's my code

#include <stdio.h>  
#include <string.h>   
#include <assert.h>  

struct lnode  
{  
  char* word;  
  int   line;  
  int   count;  
  struct lnode* nn;     /* nn = next node */  
};

struct lnode* newNode (char* word, int line) 
{
  struct lnode* newn = (struct lnode*) malloc(sizeof (struct lnode));
  if (!newn)
    return NULL;
  strcpy (newn->word, word);
  newn->line  = line;
  newn->count = 1;
  newn->nn    = NULL;
  return newn;
}

int main()
{
  char* p = "hello";
  struct lnode* head = newNode (p, 5);
  //the following lines are causing errors
  assert (!strcmp (head->word, p));     
  assert (head->line  == 5);
  assert (head->count == 1);
  assert (!head->nn);
  return 0;
}

Thanks for the help!

Community
  • 1
  • 1
Joshua
  • 5
  • 3

2 Answers2

2

Apart from the obvious problem, that you missed to include stdlib.h, there is also a problem with how you handle strings.

In C, you (yes you), have to manage all the memory that you use for strings. This includes the memory pointed to by the member word.

You code does the following (after removing some fluff):

struct lnode* newn = malloc(...);
strcpy (newn->word, word);

Here, newn->word is uninitialized, so this will likely crash.

You will need allocate memory to store the string, for example by calling malloc() a second time:

struct lnode* newn = malloc(...);
newn->word = malloc(strlen(word) + 1);
strcpy (newn->word, word);
Lindydancer
  • 25,428
  • 4
  • 49
  • 68
1

The code must have access to the structure of struct lnode.

As Alok Save hinted, you probably have the declaration in another file (a header perhaps) and you forgot to #include it.

Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82