简体   繁体   English

使用malloc创建动态结构数组

[英]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 . 问题是我从文件中读取了内容,并且不允许在scanf之后初始化该结构。 The thing is that I want to create x amounts of structs of the type vinnareinfo. 问题是我想创建x个vinnareinfo类型的结构。 I can add that we are only allowed to use C90 since it's a school project. 我可以补充一点,因为这是一个学校项目,所以我们只能使用C90。 Would really apreciate all the help out there! 真的很感谢那里的所有帮助! :D :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. 注意可能需要将fscanf格式化字符串中的'*'替换为'19',并删除'sizeof(vinnare-> ...)-1'参数。 That works for printf, but should be tested for scanf! 这适用于printf,但应该对scanf进行测试!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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