Ceasar
Ceasar

Reputation: 23083

What does "type name requires a specifier or qualifier" mean?

So I'm new to C and I'm trying to implement a cart via a linked list as follows.

typedef struct {
  char *name;
  int count;
  struct node *next;
} item;


struct cart {
  item *curr, *head;
  head = NULL;

};

When I go to compile though, I get the following errors:

ceasarb@ampersand:~> clang shopper.c 
shopper.c:14:3: error: type name requires a specifier or qualifier
  head = NULL;
  ^
shopper.c:14:3: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
  head = NULL;
  ^~~~
shopper.c:14:3: error: duplicate member 'head'
shopper.c:13:16: note: previous declaration is here
  item *curr, *head;
               ^
shopper.c:14:7: error: expected ';' at end of declaration list
  head = NULL;
      ^
      ;

I'm guessing the root of the problem is

 type name requires a specifier or qualifier

But I can't figure out what that means.

Upvotes: 2

Views: 14565

Answers (3)

pmg
pmg

Reputation: 108938

You cannot assign to head. head is not an object: it is the name of a member of a structure.

What you can do (outside the struct definiton) is assign to the head part of an object of type struct cart

struct cart object;
object.head = NULL;

or, in C99, initialize that member with a value

struct cart object = { .head = NULL };

Upvotes: 1

Jon
Jon

Reputation: 437404

It means that you what you have written (head = NULL;) is not valid in the context in which you wrote it (the definition of a struct). You can only define what your struct contains, and not initialize it by assignment.

The best you can do portably is create your struct with

struct cart my_cart = { NULL, NULL }; 

in which the NULLs initialize struct members in order of appearance in the struct definition (first NULL is assigned to curr, second one to head).

Upvotes: 1

Blagovest Buyukliev
Blagovest Buyukliev

Reputation: 43508

Assignments are not allowed within a struct definition, this is your problem.

In order to initialise head to NULL, you should declare an instance of that struct and use the appropriate initialiser:

struct cart {
  item *curr, *head;
} sample_cart = {
  NULL, NULL,
};

The head and curr fields of sample_cart are now both NULL.

Upvotes: 4

Related Questions