繁体   English   中英

使用 typedef - C 在结构中构造

[英]Struct in a struct using typedef - C

如何在C使用typedef在另一个struct正确使用一个struct

这种方法不起作用,我不明白为什么:

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    char *nume;
    char *prenume;
    data data;
} student;

typedef struct
{
    int an,zi,luna;
} data;

int main()
{
    student Andrei;

    scanf("%s %s %d ",Andrei.nume,Andrei.prenume,&Andrei.b.an);
    printf("%s %s %d ",Andrei.nume,Andrei.prenume,Andrei.data.an);

    return 0;
}

您的代码中实际上存在许多错误!

首先,您需要先声明/定义任何struct对象,然后再将其用作另一个struct的成员。

其次,您的numeprenume成员被声明为指向字符的指针,但它们没有初始化为任何内容,也没有为这些字符串分配任何内存。

第三,您的scanf行中有一个“错字”:大概Andrei.b.an应该是Andrei.data.an

最后(我认为),因为scanf的格式字符串中有一个尾随空格,该函数至少需要一个“额外”输入字段才能完成。

这是一个潜在的“修复”,在我进行更改的地方添加了评论:

#include <stdio.h>
// <stdlib.h> // You don't use this - perhaps thinking of using "malloc" for "nume" and "prenume"??

typedef struct // This MUST be defined BEFORE it is used as a member in the following struct!
{
    int an, zi, luna;
}data;

typedef struct
{
    char nume[32];    // Here, we create fixed char arrays (strings) for "nume"...
    char prenume[32]; // ... and "prenume". You can change the sizes, as you need! 
    data data;
} student;

int main()
{
    student Andrei;
    scanf("%s %s %d", Andrei.nume, Andrei.prenume, &Andrei.data.an); // Note: removed trailing space from format!
    printf("%s %s %d", Andrei.nume, Andrei.prenume, Andrei.data.an);
    return 0;
}

暂无
暂无

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

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