简体   繁体   中英

Struct in a struct using typedef - C

How do I properly use one struct inside another struct using typedef in C ?

This method doesn't work and I can't understand why:

#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;
}

There are actually a number of errors in your code!

First, you need to declare/define any struct object before you use that as a member of another struct .

Second, your nume and prenume members are declared as pointers to characters but they are not initialized to anything, nor is any memory allocated for those string.

Third, you have a 'typo' in your scanf line: Andrei.b.an should, presumably, be Andrei.data.an .

Finally (I think), because you have a trailing space in the format string for scanf , the function will need at least one 'extra' input field in order to complete.

Here is a potential 'fix', with comments added where I've made changes:

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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