[Solved] Structs in C Error [closed]


You have several problems:

  1. Format specifiers start with a % sign. So change

    scanf("d", &element[j].age);
    

    to

    scanf("%d", &element[j].age);
    

    and

    scanf("s", &element[j].name);
    

    to

    scanf("%s", element[j].name);
    

    Wondering why I removed the & from the above scanf? It is because array names gets converted to a pointer to its first element.

  2. These

    printf("%d. Fav number: %d\n", k, &element[k].age);
    printf("%d. Fav word: %s\n", k, &element[k].name);
    

    should be

    printf("%d. Fav number: %d\n", k, element[k].age);
    printf("%d. Fav word: %s\n", k, element[k].name);
    

    because the %d in the printf expects the value(int) and not the address of the variable(int*). Similarly, %s expects a char*, not a char(*)[20]

  3. The cast here is completely wrong and should be removed:

    element[j] = (struct data) malloc(sizeof(struct data));
    

    This is done because malloc returns void* which can be assigned to any pointer type without casting.

      1. etc See other answers.

solved Structs in C Error [closed]