如何将值分配给一个结构的结构成员? [英] How to assign value to a struct member of a struct?

查看:146
本文介绍了如何将值分配给一个结构的结构成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我学习用C嵌套结构,和我想要做的是能值分配给我的结构的成员结构。我无法弄清这一点,我不想强​​迫自己初始化成员结构在结构中的初始化。为什么我总是收到一个错误,当我尝试编译此code?

  main.c中:在函数'主':
main.c中:16:23:错误:在{令牌预计前pression
  fooPerson.fullname = {富,B,巴兹};

 的#define LEN 20结构名称{
    烧焦第一[LEN]
    焦炭中间;
    最后的char [LEN]
};结构的人{
    结构的名字全名;
};诠释主(){
    结构的人fooPerson;
    fooPerson.fullname = {富,B,巴兹};    //不是这个:它的工作原理,但不是解决我所要求的
    //结构的人fooPerson = {{富,B,巴兹}};
}


解决方案

在C99开始,您可以使用复合字面常量为此:

  fooPerson.fullname =(结构名称){富,B,巴兹};

如果你坚持C89,虽然,你大多是出于运气,除非你想要做这样的事情:

  {
    结构名称N = {富,B,巴兹};
    fooPerson.fullname = N;
}

菲利克斯指出在评论认为这些都不是真正的初始化的 - 它的,只有当它发生的声明,这是不是这里的情况的一部分初始化。而,无论是分配。不过,这应该做你想做的。

I am learning about nested structs in C, and what I want to do is to be able to assign a value to my struct's member struct. I'm having trouble figuring this out, and I don't want to force myself to initialize the member struct in the initialization of the struct. Why do I keep getting an error when I try to compile this code?

main.c: In function 'main':
main.c:16:23: error: expected expression before '{' token
  fooPerson.fullname = {"Foo", 'B', "Baz"};

 

#define LEN 20

struct names {
    char first[LEN];
    char middle;
    char last[LEN];
};

struct person {
    struct names fullname;
};

int main() {
    struct person fooPerson;
    fooPerson.fullname = {"Foo", 'B', "Baz"};

    // NOT this: it works, but not the solution I'm asking for
    // struct person fooPerson = {{"Foo", 'B', "Baz"}};
}

解决方案

Starting in C99, you can use a compound literal for this:

fooPerson.fullname = (struct names){ "Foo", 'B', "Baz" };

If you’re stuck with C89, though, you’re mostly out of luck, unless you want to do something like this:

{
    struct names n = { "Foo", 'B', "Baz" };
    fooPerson.fullname = n;
}

Felix points out in the comments that neither of these are truly initialization—it’s only initialization when it happens as part of the declaration, which isn’t the case here. Rather, both are assignments. Still, this ought to do what you want.

这篇关于如何将值分配给一个结构的结构成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆