gpt4 book ai didi

c++ - 指针 float 数组的第一次机会异常

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

    int main(int argc, char** argv)
{
printf("Enter the file name:\n");
char inputFileLoc[100], outFileLoc[100];
scanf("%s", inputFileLoc);
int * n = 0;
float rcoef[2];
FILE * inFile = fopen("D:\\test.txt", "r");
FILE * outFile = fopen(outFileLoc, "w");
if (inFile == NULL)
{
printf("File not found at %s", inputFileLoc);
}
else
{

printf("How many data points should we read in?");
scanf("%i", &n);
float *xdata = (float *)calloc(sizeof(float), *n);
float *ydata = (float *)calloc(sizeof(float), *n);
for (int i = 0; i < *n; i++)
{
fscanf(inFile, "%f%f", &xdata[i], &ydata[i]);
}
fregression(xdata, ydata, rcoef);
printf("Where would you like to save the file to?\n");
scanf("%s", outFileLoc);
fprintf(outFile, "The slope and intercept are %f and %f", rcoef[0], rcoef[1]);
free(xdata);
free(ydata);
}
fclose(inFile);
fclose(outFile);
return 0;
}

我在“float *xdata = (float *).....”行收到错误,我不知道为什么?我是否缺少某种异常处理程序,因为这是我唯一能想到的事情的。

最佳答案

这是不正确的:

int * n = 0;

应改为

int n = 0;

scanf 应该获取要写入的地址,而不是指针的地址。即使您想使用指针,也应该分配内存并且 n 应该指向该指针。在这种情况下,您应该在传递给 scanf 时将 & 删除为 n,即 scanf("%i", n); 应该没问题。

关于c++ - 指针 float 数组的第一次机会异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21542581/

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