-1
struct player {
    char name[20];
    struct player *next;
};

int main() {
  struct player *p;
  p.name = "bob";
}

error: request for member 'name' in something not a structure or union

How would I set a char name with a struct?

rebel ion
  • 13
  • 2

2 Answers2

0

In that little piece of code you have multiple problems.

The first, about the error you get, you should have been told by just about any book or tutorial, good or bad. You need to use the "arrow" operator ->, as in p->name.

But then you would get another error, because you can't assign to an array, only copy to it.

And when that's done, you still have one more error, and that is your use of an uninitialized pointer. Uninitialized local variables (which is what p) is are really uninitialized. Their values will be indeterminate and seemingly random. Attempting to dereference (what you do with ->) such a pointer will lead to undefined behavior.

In short, I recommend you to go back to your text book, and start over from the beginning.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

The simplest fix is to not declare p as a pointer to a struct, but rather an actual struct....and then use strcpy() to set name. C doesn't use = for string assignment like some other programming languages.

struct player {
    char name[20];
    struct player *next;
};

int main() {
  struct player p;
  strcpy(p.name, "bob");
}
Stephen Docy
  • 4,738
  • 7
  • 18
  • 31