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

标签 c++ c pointers

    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/

相关文章:

c++ - 如何使用 c++ 2010、2012 和 2013 工具集安装一个版本的 visual studio 2013

c++ - 比较常规选择和准备选择性能

c - 尝试更新数组元素时出错

c - 返回内存地址作为函数中的参数

c - 二维字符数组的 malloc 函数的段错误

c - 为什么这段代码会出现段错误? (指针运算)

c++ - 函数被多次调用

c++ - 编写客户端和服务器,UDP

java - 为什么在 C++ 中使用 this->ObjectName 而不是 this.ObjectName

c - 当我使用 scanf() 时,我想知道这两者有什么不同