c - 如何在 C 中将文件中的整数 fscanf 到数组中?

标签 c arrays pointers

我正在做一个作业,让我开始使用数组在 C 类中进行编程,使用 fscanf 从文件中获取整数,然后打印它们。代码将构建,但当我运行它时,程序在第 31 行的 Display 函数期间停止工作。它给出的错误是“在 Project 6.exe 中的 0x00CE50F1 处抛出异常:0xC0000005:访问冲突写入位置 0x00F4D720”。我确信我在数组上做错了什么,因为我的教授在打印和扫描时将数组写成“数组[计数]”而不是“数组[&计数]”,但如果我像 Visual Studio 那样写下划线“计数”并表示“表达式必须具有指向对象的指针类型”。我并不是想欺骗,我想知道出了什么问题以及如何让它发挥作用。

   #define CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>

int Greeting();
void Display(numchosen, Numptr, array);

int main() {
    int numchosen, array[20];
    FILE * Numptr;

    Numptr = fopen("numInput.txt", "r");
    numchosen = Greeting();
    Display(numchosen, &array, Numptr);
}

int Greeting() {
    int numchosen;

    printf("How many integers should I retreive from the file? (1-20)\n");
    scanf("%d", &numchosen);

    return numchosen;
}
void Display(numchosen, array, Numptr) {
    int numprinted, numnum = 1, currentnum, count=0;


    for (numprinted = 0; numprinted < numchosen; numprinted++) {


        fscanf(Numptr, "%d", &array[&count]);
        printf("%d. %d\n", numnum, array[&count]);

        numnum ++;
        count++;
    }
}

最佳答案

声明你的参数类型!

void Display(numchosen, array, Numptr)

应该阅读

void Display(int numchosen, int *array, FILE * Numptr)

注意你的类型!

    fscanf(Numptr, "%d", &array[&count]);
    printf("%d. %d\n", numnum, array[&count]);

永远不要按某物的地址进行索引。这是类型不匹配。

    fscanf(Numptr, "%d", &array[count]);
    printf("%d. %d\n", numnum, array[count]);

这看起来是正确的。

关于c - 如何在 C 中将文件中的整数 fscanf 到数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47127835/

相关文章:

c - char 数组中不需要的文本

c - 尝试取消引用动态分配的指针时出现段错误

c++ - OpenCV : convert the pointer in memory to image

c - scanf 到结构中的字段的问题

c - C语言中AT命令的使用方法

c - 执行 Ansi C 标准检查的 GCC 选项?

c - 打印指针值

C++ 输入输出排序

arrays - 如何在 iOS Swift 中的嵌套数组(对多关系)中根据条件过滤对象数组

c++ - 具有未定义第二维的二维数组