简体   繁体   English

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

[英]how to read integer int* from text in c

I have this structure and a structure for AVL tree 我有这个结构和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;
};

What i want to do is to populate this AVL structure with some text from txt file, and it crashes when i try to read that integer int*. 我想做的是用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);
}

You need to allocate space for noOfPeopleLivingInApartments before you can read into the elements. 您需要先为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]);
}

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

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