指针浮动阵列的第一个机会例外

First chance exception with pointer floating array

本文关键字:一个机会 阵列 指针      更新时间:2023-10-16
    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);应该很好。

  1. int *n 更改为 int n 当您试图写入未初始化的内存时。

  2. 在calloc中也进行了更改,因为它试图从 *n分配,该更改未正确定义

尝试进行两个更改时,它可以正常工作。即使在此之后您会遇到错误。