Home > Back-end >  Returning a structure results in gibberish
Returning a structure results in gibberish

Time:12-02

I'm using structures in C and when I try to return a structure from a function it always results in gibberish when I try to print the contents of that structure in main. Here is my code :

#include <stdio.h>
struct etudiant
{
    int a;
    int b;
    int c;
};
typedef struct etudiant ETD;

ETD ajouter_etd()
{
    ETD e;
    scanf("%i%i%i", e.a, e.b, e.c);
    return e;
}

void main()
{
    ETD e;
    e = ajouter_etd();
    printf("%i%i%i", e.a, e.b, e.c);
}

CodePudding user response:

You must pass the addresses of your variables to scanf as it needs to know where in memory to place the results of its conversions. This is done with the address-of operator (&).

#include <stdio.h>

typedef struct etudiant {
    int a;
    int b;
    int c;
} ETD;

ETD ajouter_etd(void)
{
    ETD e;
    scanf("%i%i%i", &e.a, &e.b, &e.c);
    return e;
}

int main(void)
{
    ETD e;
    e = ajouter_etd();
    printf("%i%i%i\n", e.a, e.b, e.c);
}
  • Related