0

I have 2 structs using pointers to form a linked list.

typedef struct { 
    char *text;
    int count;
} *Item;

typedef struct node {
    Item item;
    struct node *next;
} *link;

Im trying to create a bunch of operations over this type but I'm having a lot of problems with this particular function.

error: request for member ‘text’ in something not a structure or union strcpy(new->item->text, buffer->text);

error: request for member ‘text’ in something not a structure or union new->item->text = (char*) malloc(sizeof(char)*(strlen(buffer->text)+1));

Basically the error is on the buffer->text pass, but I've been messing around with it for the past hour and can't seem to find what's wrong with it. I'm probably missing something obvious but I can't wrap my hear around it anymore.

link new_item(Item* buffer) {
   link new = (link) malloc(sizeof(struct node));
   new->item->text = (char*) malloc(sizeof(char)*(strlen(buffer->text)+1));
   strcpy(new->item->text, buffer->text);
   new->item->count = 1;
   new->next = NULL;
   return new;
}
spacing
  • 730
  • 2
  • 10
  • 41
  • 5
    The message sometimes means you're using `.` where `->` should be used, or vice versa. Alternatively, it means that the LHS of the reference is neither a pointer to a structure nor a structure; and that's your problem here. See [Is it a good idea to typedef pointers](http://stackoverflow.com/questions/750178/is-it-a-good-idea-to-typedef-pointers) — the answer's "No" because it leads to problems like this. The variable `buffer` is a pointer to a pointer to a structure; you need to use `(*buffer)->text` etc. Or you need to change the function to `link new_item(Item buffer)`. – Jonathan Leffler May 14 '16 at 06:31

1 Answers1

3

The problem is that you have two levels of indirection instead of just one. Specifically, buffer has type Item *, while Item is a struct {...} *. You probably want to change Item *buffer to just Item buffer. If you really need two levels of indirection, then you would need to do (*buffer)->text to access the text field, but this probably isn't what you want.

This is one of the reasons why many people advise against using typedef to define pointer types, as it can often lead to mistakes like this.

Community
  • 1
  • 1
Tom Karzes
  • 22,815
  • 2
  • 22
  • 41