c - for 中的声明给出了段错误

标签 c

我正在做学习图表的作业。为此,我将获取一个 csv 文件并将该信息保存在传感器结构中。

#define sensor_amount 70
typedef struct Sensor {
    int id;
    float x,y,z;
}Sensor; 

为了从文件中获取此结构,我使用以下函数:

Sensor* get_sensors(char* file_name){
    FILE* file = fopen(file_name,"r");
    //Skip first line
    char* c;
    fscanf(file,"%[^\n]",c);

    int id = 0;
    float x,y,z;

    Sensor* sensor_arr = malloc(sizeof(Sensor));
    fscanf(file,"%i,%f,%f,%f",&id,&x,&y,&z);
    sensor_arr[0].id = id;
    sensor_arr[0].x = x;
    sensor_arr[0].y = y;
    sensor_arr[0].z = z;

    int counter = 1;

    while(!feof(file)){
        fscanf(file,"%i,%f,%f,%f\n",&id,&x,&y,&z);
        ++counter;
        sensor_arr = realloc(sensor_arr,counter*sizeof(Sensor));
        sensor_arr[counter-1].id = id;
        sensor_arr[counter-1].x = x;
        sensor_arr[counter-1].y = y;
        sensor_arr[counter-1].z = z; 
    }
    fclose(file);
    return sensor_arr;
}

我使用以下代码计算每个传感器之间的距离:

float** get_distances(Sensor* s){
    float** a = malloc(sensor_amount*sizeof(float*));

    for(int i = 0; i < sensor_amount;i++)
        a[i] = malloc(sensor_amount*sizeof(float));

    for(int i = 0; i < sensor_amount;i++){
        for(int j = 0; j < sensor_amount; j++){
            float dis = distance(s[i].x,s[i].y,s[j].x,s[j].y);
            a[i][j] = dis;
        }
    }
    return a;
}

最后在我的 main 中我打印这些值,如下所示:

int i,j;
int main(){
    char file_name[] = "sensor_locations.csv";
    Sensor* sensors; 
    sensors = get_sensors(file_name);
    float**ar=get_distances(sensors);
    for(i=0;i < 70; ++i)
        for(j=0;j<70;++j){
            printf("(%i,%i)->%f\n",i,j,ar[i][j]);
    }
    return 0;
}

在 main 中,如果我将 i 和 j 的声明移至 for 循环,则会引发段错误。但为什么呢?

最佳答案

这是为数组越界错误而设计的:

int counter = 1;
...
++counter;
...
[counter-1]

相反

for(int i=0; more_data; i++)
{
  sensor_arr[i] = ...;
  sensor_arr = realloc(sensor_arr,(i+2)*sizeof(Sensor));
}

请注意Why is “while ( !feof (file) )” always wrong? .

并且您对 realloc 的使用是错误的,请使用 tmp 指针来存储结果,并在将其分配回 sensor_arr 指针之前检查其是否为 NULL。

关于c - for 中的声明给出了段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58817884/

相关文章:

c : matrix multiplication without * operator

c - 我不知道为什么代码中的输入会被回退。 C语言

c - 如何在c中划分2个整数?

c - 使用 dbus 的简单客户端服务器

python - 使用 SWIG 从 Python 向 C 传递数组参数

c - 从管道(FIFO)读取然后比较字符串

c - OpenGL:如何使用鼠标拖动图像并将其移动到直线

c - 如何从字符数组中提取子字符数组

c - 是否可以在具有 32 位处理器的机器上运行 64 位代码?

在 C 中将一维数组转换为二维数组