0

I am working on a code to write and read information from a struct that has a pointer type variable and everything works well so far but, when i try to clean the screen with system("CLS"); the program exits but this only happens after reading the string persona[cx].nombre.

I tried using different ways of reading the string (getchar(), scanf(" %s") and scanf(" %c)) but that doesn't seems to help. I guess that this problem is something related to the pointer variable because pointers and structs are both new for me so maybe i am missing something.

here is the code i've made so far:

    struct datos{
        char nombre[30];
        int edad;
        char sexo;
    } *persona;

    void arreee(int *);
    int main(){
        int me = 0;
        persona = malloc(sizeof(char[1]));
        printf("\n  Repeticiones: ");
        scanf("%d", &me);
        fflush(stdin);
        persona = realloc(persona, me);
        arreee(&me);
        printf("\n.  .  .\nDone! %d\n.  .  .\n>", me);
        getchar();
        return 0;
    }

    // funciones

    void arreee(int *e){
        int cx, i;

        for(cx = 0; cx < *e; cx++)
        {
            printf("\nsexo? m/f\n> ");
            scanf("%1c", &persona[cx].sexo);
            fflush(stdin);
            printf("\nnombre> ");
            fgets(persona[cx].nombre, 30, stdin);
            fflush(stdin);
            printf("\nedad> ");
            scanf("%d", &persona[cx].edad);
            fflush(stdin);
            system("cls");
        }

        for(i = 0; i < *e; i++)
        {
            printf("Sexo %c    Edad %d     Nombre %s", persona[i].sexo, persona[i].edad, persona[i].nombre);
        }
    }
xtealer
  • 1
  • 4
  • 1
    You are not allocating enough memory: `persona = malloc(sizeof(struct datos));` Or `persona = malloc(sizeof(*persona));` - same thing. – Johnny Mopp Nov 06 '18 at 03:12
  • For starters, you should NEVER [fflush(stdin)](https://stackoverflow.com/a/2979217/1553090) – paddy Nov 06 '18 at 03:12
  • I use malloc to allocate the variable for the first time in memory, later i use realloc to allocate enough memory to do as many reads as requested by the user. The code works fine if i don't use system("CLS"). – xtealer Nov 06 '18 at 04:22
  • You do not `realloc` enough mem either: `persona = realloc(persona, me * sizeof(struct datos));` – Johnny Mopp Nov 06 '18 at 04:29
  • Also, there is no need to `realloc`. Move the `malloc` to after you read `me` and get the mem: `persona = malloc(me * sizeof(struct datos));` – Johnny Mopp Nov 06 '18 at 04:32
  • Thanks a lot!!! That worked like a charm :D. I'll pay more attention to malloc now onways. – xtealer Nov 06 '18 at 05:06

0 Answers0