在中声明会产生细分错误

时间:2019-11-12 11:34:37

标签: c

我正在做作业来学习图形。为此,我要获取一个csv文件,并将该信息保留在Sensor结构中。

#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;
}

最后,在我的主菜单中,我打印出这些值:

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;
}

总的来说,如果我将i和j的声明移至for循环,则会引发分段错误。但是为什么呢?

1 个答案:

答案 0 :(得分:0)

这是为解决数组错误而设计的:

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。