gpt4 book ai didi

c - 程序不运行。说我正在尝试为指针赋值

转载 作者:行者123 更新时间:2023-11-30 21:34:54 25 4
gpt4 key购买 nike

我正在尝试将文件读入数组,但代码未运行。说我正在尝试为指针赋值。

 #include <stdio.h>

int main(void)
{
FILE *ifile;
float num;
float*numbers[8001];
float pointer = numbers;
int i = 0;

ifile = fopen("lotsOfNumbers.txt", "r");
if (ifile == NULL) {
printf("File not found!! Exiting.\n");
}
else {
while (fscanf(ifile, "%f ", &num) != EOF) {

//printf("I read %d from the file. \n", num);
numbers[i] = &num;

if (i < 8801) {
i++;
}
else return 0;
}
}

fclose(ifile);
}

最佳答案

您的代码中有很多错误。您可能想要这个:

#include <stdio.h>

int main(void)
{
FILE *ifile;
float num;
float numbers[8001]; // you just need an array of float, no pointers needed
int i = 0;

ifile = fopen("lotsOfNumbers.txt", "r");
if (ifile == NULL) {
printf("File not found!! Exiting.\n");
}
else {
while (fscanf(ifile, "%f ", &num) != EOF) { // &num instead of num

printf("I read %f from the file.\n", num); // use %f for printing a float, not %d
numbers[i] = num;

if (i < 8001) { // 8001 instead of 8801
i++; // using a constant or a #define avoids this kind of errors
}
else
return 0;
}

fclose(ifile); // close file only if it has been opened sucessfully
}
// fclose(ifile); // that was the wrong place for fclose
}

解释在评论中。

关于c - 程序不运行。说我正在尝试为指针赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55860628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com