c - 如何从c中的文本中读取整数int *

标签 c file text integer int

我有这个结构和一个AVL树的结构

struct imobil
{
    unsigned int id;
    char *streetName;
    unsigned int streetNumber;
    int noApartaments;
    int *noPeopleLivingInApartaments;
    float totalValue;
};

struct nodeAVL
{
    imobil inf;
    nodeAVL *right;
    nodeAVL *left;
    int BF;
};

我想做的是用 txt 文件中的一些文本填充这个 AVL 结构,当我尝试读取那个整数 int* 时它崩溃了。

void main()
{
 FILE *f = fopen("Imobil.txt", "r");
 int n;
 nodeAVL *root = (nodeAVL*)malloc(sizeof(nodeAVL));
 imobil imob;
 char buffer[20];

fscanf(f, "%d", &n);
for (int i = 0; i < n; i++)
{
    fscanf(f, "%d", &root->inf.id);
    fscanf(f, "%d", &root->inf.streetNumber);
    fscanf(f, "%s", &buffer);
    root->inf.streetName= (char*)malloc((strlen(buffer)+1)*sizeof(char));
    strcpy(root->inf.streetName, buffer);
    fscanf(f, "%f", &root->inf.totalValue);
    fscanf(f, "%d", &root->inf.noApartaments);
    for (int i = 0; i < root->inf.noApartaments;i++)
        fscanf(f, "%d", &root->inf.noPeopleLivingInApartaments[i]);
    inserare(imob, root);
}
fclose(f);
preorder(root);
deallocation(root);
}

最佳答案

在读取元素之前,您需要为 noOfPeopleLivingInApartments 分配空间。

root->inf.noPeopleLivingInApartaments = malloc(root->inf.noApartaments * sizeof(int));
for (int i = 0; i < root->inf.noApartaments;i++) {
    fscanf(f, "%d", &root->inf.noPeopleLivingInApartaments[i]);
}

关于c - 如何从c中的文本中读取整数int *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44577094/

相关文章:

c - 在结构中如何存储值?

结构体中的 C 函数指针在调用时不会更改值

PHP 将文件读入数组

Android openFileOutput - 没有创建存储的权限

python - 如何将文本文件转换为Excel文件,而不删除数据之间的空格

c - 如何解决创建 MessageBox 时的类型转换警告

ios - Swift:将 NSDictionary 保存到文件中,因为 NSUserDefaults 会变慢

regex - 替换两个特殊字符之间的文本

c# - 搜索大量大文本列表的最快方法

c - C 中 strftime() 函数中的奇怪格式说明符