c - Acces data in a structure array -
i'm not understanding how have use pointer structures. i'm trying simple example, 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 program crash? how should put int value in structure?
your program crashing because passing uninitialized int scanf() expects pointer int. suspect compiling withtout warnings enabled, since learning highly recommend enabling compiler warnings.
to use scanf() need check it's return value, this
if (scanf("%d", &dati->codigo_postal) != 1) do_something_because_codigo_postal_is_not_initialized(); you must pass pointer local variable let scanf() able store value in it, if pass variable it's value considered address scanf() attempt store result, leads undefined behavior, , variable never initialized yet cause undefined behavior.
also, don't use malloc() check it's returned value. rewrite code 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) 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; }
Comments
Post a Comment