C 为什么我会有分割错误?
分段错误与随机数无关,因为您从未为辅助结构坐标分配内存 要解决此问题,请使用以下方法:C 为什么我会有分割错误?,c,random,struct,segmentation-fault,C,Random,Struct,Segmentation Fault,分段错误与随机数无关,因为您从未为辅助结构坐标分配内存 要解决此问题,请使用以下方法: typedef struct { unsigned char deg, min, sec; }angle_t; typedef struct { angle_t latitude, longitude; }st_coord_t; typedef struct { float SDM; size_t ID;
typedef struct {
unsigned char deg, min, sec;
}angle_t;
typedef struct {
angle_t latitude, longitude;
}st_coord_t;
typedef struct {
float SDM;
size_t ID;
st_coord_t * coordinates;
}st_record_t;
当不再使用时,请记住释放内存。您已经释放了内存
aux_struct.coordinates = malloc(sizeof(st_coord_t));
如您所见,coordinates
是类型为st\u coord\t
的指针。您需要使用malloc
为其分配内存:
typedef struct {
float SDM;
size_t ID;
st_coord_t * coordinates;
}st_record_t;
使用后,您需要释放分配的内存,请使用:
aux_struct.coordinates=malloc(sizeof(st_coord_t));
请注意,如果要使用它并在使用后释放它,则必须为
aux2_struct
中的坐标分配内存。除了缺少“coordinates”成员初始化的问题外,还应该指出fwrite()不会执行您想要的操作。它将只写st_记录的内容。指针“坐标”的值在进行写入的进程之外没有任何意义,它所指向的st_coord_t结构中的数据将根本不会被写入
您可能想看看hdf5之类的东西,以便以可移植的方式将复杂的二进制数据结构写入文件。因为aux_struct.coordinates
从未初始化过。它是一个指向未指定位置的指针,调用未定义的行为。在哪里初始化aux_struct.coordinates数组?我认为应该分配的是aux_struct:)尽管他定义了st_record_t aux_struct和aux2_struct;不曾malloc@KCdodaux_struct
本身不是指针,不需要分配内存。谢谢,就是这样。你知道为什么,当我运行它时,我总是得到相同的数字吗?SDM字段除外。谢谢你的帮助@SantiagoAguilar在使用rand
之前,您需要先调用srand
一次,然后才能使用谷歌的rand
。
aux_struct.coordinates=malloc(sizeof(st_coord_t));
free(aux_struct.coordinates);