简体   繁体   English

如何使用结构指针设置字符名称?

[英]How to use struct pointer to set char name?

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? 如何设置带有结构的字符名称?

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 . 您需要使用“ arrow”运算符-> ,如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. 未初始化的局部变量(即p )实际上是未初始化的。 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. 简而言之,我建议您回到课本上,从头开始。

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 . 最简单的解决方法是不将p声明为指向结构的指针,而是将其声明为实际的struct ....,然后使用strcpy()设置name C doesn't use = for string assignment like some other programming languages. C不像其他编程语言那样使用=进行字符串分配。

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

int main() {
  struct player p;
  strcpy(p.name, "bob");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM