I'm doing a homework for learning graphs. For that, I'm taking a csv file and I keep that information in a Sensor structure.
#define sensor_amount 70
typedef struct Sensor {
int id;
float x,y,z;
}Sensor;
For getting this struct from file I'm using the following function:
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;
}
I'm calculating distances between each sensor with following code:
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;
}
Finally in my main i print those values like this:
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;
}
In main, if I move the declarations of i and j to the for loops, it throws a segmentation fault. But why?