我不明白为什么人类不兼容?我需要做什么来编译它?

时间:2015-02-13 02:30:38

标签: c compiler-errors allocation

我迷失在这里,我不明白为什么s = (struct Person *)malloc(sizeof(struct Person) * n);无法工作?此分配是在data.txt文件中查找BMI。其中只包含此内容

3 Pikachu 50 37 Godzilla 1000 1000 Holmes 178 67

并将其输出到BMI.txt文件中。需要分配内存块。提前谢谢。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define STUDENT 3

struct Person {
float   mass, height;
float   bmi;
int     count, num;
char    name[99];
};

typedef struct Person Person;

int main()
{
int i;

FILE *in, *out;
in = fopen("data.txt", "r");
if (in == NULL) {
    printf("failed to open file!\n");
    exit(1);
}
out = fopen("bmi.txt", "w");

struct Person s[STUDENT];

s = (struct Person *)malloc(sizeof(struct Person) * i);
for (i = 0; i < 3; i++) {
    fscanf("%s", &s[i].name);
    fscanf("%lf", &s[i].height);
    fscanf("%lf", &s[i].weight);
    bmi = mass / (pow(height, 2));
    fprintf(out, "%s%3.2f\n", name, bmi);
}
free(s);
}
fclose(in);
fclose(out);

}

1 个答案:

答案 0 :(得分:1)

s = (struct Person *)malloc(sizeof(struct Person) * n);

不仅错误,而且不必要,s已经是struct Person的数组,因此您无法分配,并且您不需要malloc()空间

也许你需要这个

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define STUDENT 3

struct Person {
    int     mass, height;
    int     bmi;
    int     count, num;
    char    name[99];
};

typedef struct Person Person;

int main()
{
    int            i;
    int            n;
    struct Person *s;
    FILE          *in;
    FILE          *out;

    in = fopen("data.txt", "r");
    if (in == NULL) {
        printf("failed to open file!\n");
        exit(1);
    }
    out = fopen("bmi.txt", "w");
    if (out == NULL) {
        printf("failed to open file!\n");
        fclose(in);
        exit(1);
    }
    n = 3;
    s = malloc(sizeof(struct Person) * n);
    if (s == NULL) {
        printf("failed to open file!\n");
        fclose(in);
        fclose(out);
        exit(1);
    }

    for (i = 0; i < n; i++) {
        fscanf("%s", s[i].name);
        fscanf("%d", &s[i].height);
        fscanf("%d", &s[i].mass);

        bmi = mass / (pow(height, 2));

        fprintf(out, "%s%d\n", name, bmi);
    }
    free(s);
    fclose(in);
    fclose(out);
}

并且无需从void *转换为任何其他指针类型,因此请勿投射malloc()