Home Ask Login Register

Developers Planet

Your answer is one click away!

Marco February 2016

Acces data in a structure array

I'm not understanding how i have to use pointer to structures. I'm trying with a very simple example, but it's not working.

typedef struct
{
char nombre [100], domicilio [200];
int codigo_postal, nro_documento;
unsigned char edad_sexo;
}
t_persona;

int main()
{
int edad;
char sexo;
t_persona* dati=malloc(sizeof(t_persona));
scanf("%d",(*dati).codigo_postal);
    return 0;
}

Why does my program crash? How should i put the int value in the structure?

Answers


iharob February 2016

Your program is crashing because you are passing an uninitialized int to scanf() where it expects a pointer to int. I suspect you are compiling withtout warnings enabled, since you are learning I highly recommend enabling compiler warnings.

To use scanf() you also need to check it's return value, something like this

if (scanf("%d", &dati->codigo_postal) != 1)
    do_something_because_codigo_postal_is_not_initialized();

you must pass a pointer to your local variable to let scanf() be able to store the value in it, if you just pass the variable it's value will be considered an address where scanf() will attempt to store the result, that leads to undefined behavior, and also your variable was never initialized which is yet another cause for undefined behavior.

Also, don't use malloc() like that always check for it's returned value. I would rewrite all your code like this

typedef struct
{
    char nombre[100];
    char domicilio[200];
    int codigo_postal;
    int nro_documento;
    unsigned char edad_sexo;
} t_persona;

int main()
{
    t_persona *dati = malloc(sizeof(*dati)); // Use sizeof(*dati) which is
    if (dati == NULL)                        // far more maintainable.
        return -1; // `malloc()' failed
    if (scanf("%d", &dati->codigo_postal) != 1)
        return -1; // input error
    fprintf(stderr, "%d\n", dati->codigo_postal);
    free(dati);
    return 0;
}

Post Status

Asked in February 2016
Viewed 3,136 times
Voted 9
Answered 1 times

Search




Leave an answer


Quote of the day: live life