printf没有打印正确的号码

时间:2014-12-18 09:42:54

标签: c printf

我有这个作为我的结构

    struct theFile{
        int count;
        FILE *fPointer;
        int *fileItems[];
    }myFile;

这是我将文件保存在fileItems中的方法。它正确地保存了数字。例如fileItems[0] = 5fileItems[1] = 45fileItems[2] = 35

    void saveFile(){
        myFile.fPointer = fopen("mileage.txt", "r");
        int i = 0;

        while (!feof(myFile.fPointer)){
            myFile.fileItems[i] = (int*)malloc(sizeof(int));
            fscanf(myFile.fPointer, " %d,", myFile.fileItems[i]);
            i++;
        }
        myFile.count = i;
    }

但是当我用这种方法打印文件的内容时,它将正确打印第一个数字,然后它会将其余数字打印为大数字。有人可以告诉我为什么它不打印正确的阵列内容。

    void viewFile(){
        for(int i = 0; i < myFile.count; i++){
            printf("%d, ", myFile.fileItems[i]);
        }
    }

另请注意,它是用c。

编写的

3 个答案:

答案 0 :(得分:2)

int *fileItems[];等于int ** fileItems; 很可能你想要一个整数数组,而不是整数指针数组。

将结构声明更改为int * fileItems;,并在循环之前分配一次列表:

myFile.fileItems = malloc(sizeof(int) * initialNumberOfElements);

稍后,如果initialNumberOfElements太小,则在realloc更多空间:

myFile.fileItems = realloc(myFile.fileItems, sizeof(int) * biggerElementCount);

然后fscanf的参数必须是&myFile.fileItems[i]

请勿忘记在分配功能失败时添加错误处理代码。对于您使用的任何文件函数也是如此:所有I / O都可能失败。

答案 1 :(得分:1)

fscanf要求指针作为参数,但它通常是现有int的地址,而不是“真正的”int*。你可能想写:

struct theFile{
    int count;
    FILE *fPointer;
    int fileItems[N]; // You need to put a value as N, like 10, or else the array will be of size 0
}myFile;

然后

fscanf(myFile.fPointer, " %d,", &myFile.fileItems[i]); // with a & to get the address

这样您就不需要mallocfree。其余的就好了。

编辑:如果您不知道预先有多少int,那么user694733的答案会更好。

答案 2 :(得分:0)

在结构中进行声明。

struct theFile{
    int count;
    FILE *fPointer;
    int *fileItems[MAX];// MAX=10;
}myFile;

空数组下标无法知道如何指向数组。