c - 使用 fscanf 读取 C 中的坐标时出现问题

标签 c segmentation-fault coordinates scanf

我知道有人问过类似的问题,但似乎没有一个能解决我的问题。我在运行代码时遇到 Segmentation fault (core dumped)

“data.dat”中的第一行是文件中点的总数,接下来的几行是点坐标(二维)。我使用 fgets 读取第一行,然后使用 fscanf 读取下一行。

这是我的代码:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    int n = atoi(argv[1]);
    FILE *fp;
    fp = fopen("data.dat","r");
    if (fp == NULL) {
        perror("Error");
    }

    int number;
    char str[3];

    fgets(str, 3, fp);
    number = atoi(str); // number of points to read from the file
    printf("number of lines: %d\n", number);

    // defining matrix to hold points
    float *P = (float *) malloc(sizeof(float)*2*number);

    int i = 0;
    while(i < number){
        int ret = fscanf(fp, "%f%f", P[i*number + 1], P[i*number + 2]);
        printf("%f  %f", P[i*number + 1], P[i*number + 2]);
        if (ret == 2){
            i++;
        }
    }
    fclose(fp);
    return 0;
}

编译它没有给我任何错误,但它确实给了我以下警告:

polynom.c: In function ‘main’:
polynom.c:32:24: warning: format ‘%f’ expects argument of type ‘float*’,but argument 3 has type ‘double’ [-Wformat=]

int ret = fscanf(fp, "%f%f", P[i*number + 1], P[i*number + 2]);
                    ^
polynom.c:32:24: warning: format ‘%f’ expects argument of type ‘float *’, but argument 4 has type ‘double’ [-Wformat=]

我不太明白,因为我确实将参数 3 定义为 float 。

我使用命令行变量运行代码,因此不会出现段错误。

最佳答案

应该是

while (2 == fscanf(fp, "%f%f", &P[i], &P[i+1]) {
    i += 2;
    if (i >= number*2)
        break;
}

关于c - 使用 fscanf 读取 C 中的坐标时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30403869/

相关文章:

C 与 OpenMP : Matrix times vector

c - 如何在仍显示屏幕的同时将所有输出保存到屏幕上?

c++ - 将节点附加到链表时出现段错误

swift - 使用 Polyline (Swift) 使用 MKMapView 绘制坐标

opencv - 提取霍夫线交点坐标并将数据获取到记事本或 Excel

c - 用 define C 替换函数调用(而不是声明)

c - 如何用 LuaJIT 定义 C 函数?

c - fopen/fclose 上的段错误

c - 运行循环 41881 次时出现段错误

r - 是否有解决方法来获得 googlemaps 未涵盖的点(长纬度)之间的旅行时间(使用 gmapsdistance)?