简体   繁体   中英

Creating dynamic struct arrays using malloc

I have a problem regarding creating dynamic struct arrays. The thing is I read from a file and I am not allowed to initialize the struct after the scanf . The thing is that I want to create x amounts of structs of the type vinnareinfo. I can add that we are only allowed to use C90 since it's a school project. Would really apreciate all the help out there! :D

#include <stdio.h>

struct vinnareinfo{
    char fornamn[20];
    char efternamn[20];
    int ar;
    };

main(){


struct vinnareinfo *vinnare;

int i = 0, x;
FILE *file;

file = fopen("C:\\Uppgifter.txt", "r");
if (file != NULL){
    fscanf(file, "%d", &i);
}
else{
    printf("Ange antal vinnare:");
    scanf("%d", &i);
    i = i - 1;



    for (x = 0; x < i; x++){
        printf("Ange år: ");
            scanf("%d", ??? )
        }
    }
}
#include <stdlib.h>
...

printf("Ange antal vinnare:");
scanf("%d", &i);
//i = i - 1;//remove

vinnare = malloc(i * sizeof(struct vinnareinfo));//check return value of malloc

for (x = 0; x < i; x++){
    printf("Ange ar: ");
    scanf("%d", &vinnare[i].ar);
}

to make things easier and more readable consider defining a new data type for your structure:

    typedef struct {
    char fornamn[20];
    char efternamn[20];
    int ar;
    }vinnareinfo;

You can find more useful info about it here

scanf("%d", &i);
vinnareinfo *v = (vinnareinfo*)malloc((i-1)*sizeof(vinnareinfo)); //allocated an array of i elements of type  vinnareinfo 

I hope this is what you were looking for.

if (fscanf(file, "%d", &i) != 1) {
    perror("fscanf");
    exit(1);
}

vinnare = malloc(sizeof(struct vinnareinfo) * i);
if (!vinnare) {
    perror("malloc");
    exit(1);
}

for (x = 0; x < i; x++) {
    int rc = fscanf(file, "%*s%*s%d",
        sizeof(vinnare->fornamn)-1,   &vinnare->fornamn,
        sizeof(vinnare->efternamn)-1, &vinnare->efternamn,
        &vinnare->ar);
    vinnare++;
    if (rc <= 0) {
        perror("fscanf");
        break;
    }
}

NB May be need to replace '*' in fscanf formatting string by '19', and remove 'sizeof(vinnare->...)-1' args. That works for printf, but should be tested for scanf!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM