我是一名获得硕士学位的软件工程师,我正在用C编写一个实现Lloyd算法的程序。然而,我陷入了这个分割错误11.我正在处理大数字,这就是它崩溃的原因,但我已经尽可能多地渲染它,但我仍然会遇到这个错误。
这些是实现的结构:
struct point{
float x;
float y;
};
struct cluster{
float x;
float y;
float* points;
};
这是我的代码:
struct point* initPoint(){
struct point* point = malloc(sizeof(struct point));
point->x = 0.0;
point->y = 0.0;
return point;
}
struct cluster* initCluster(int NP){
struct cluster* cluster = malloc(sizeof(struct cluster));
cluster->x = 0.0;
cluster->y = 0.0;
cluster->points = malloc(sizeof(float)*NP);
return cluster;
}
void init(int NP, int NC, struct point* points[NP], struct cluster* clusters[NC]) {
for(int p = 0; p < NP; p++){
points[p] = initPoint();
}
for(int i = 0; i < NC; i++){
clusters[i] = initCluster(NP);
}
srand(10);
for(int p = 0; p < NP; p++) {
points[p]->x = (float) rand() / RAND_MAX; // coordinate X
points[p]->y = (float) rand() / RAND_MAX; // coordinate Y
}
for(int i = 0; i < NC; i++) {
clusters[i]->x = points[i]->x;
clusters[i]->y = points[i]->y;
}
}
void free_structs(int NP, int NC, struct point* points[NP], struct cluster* clusters[NC]){
for(int i = 0; i < NP; i++){
free(points[i]);
}
for(int i = 0; i < NC; i++){
free(clusters[i]->points);
free(clusters[i]);
}
}
在主文件中:
#define N 10000000 // number of points (NP)
#define K 4 // number of clusters (NC)
int main(){
struct point* points[N];
struct cluster* clusters[K];
init(N,K,points,clusters);
/*
for(int i = 0; i < K; i++){
printf("Cluster --> %d: n",i);
printf("Coordinate X: %fn",clusters[i]->x);
printf("Coordinate Y: %fnn",clusters[i]->y);
}*/
free_structs(N,K,points,clusters);
return 0;
}
你能帮我一把吗?
问题很可能是您试图在堆栈上分配太多。我建议您为大型数组动态分配内存(在堆上(。
在main
中,更改自:
struct point* points[N];
struct cluster* clusters[K]; // K is only 4, but I expect you may increase it later
至
struct point** points = malloc(N * sizeof *points);
struct cluster** clusters = malloc(K * sizeof *clusters);
// then at the end of main:
free(clusters);
free(points);
此外,为了使init
可移植到不支持VLA的实现中,请更改为:
void init(int NP, int NC, struct point* points[NP], struct cluster* clusters[NC]) {
至
void init(int NP, int NC, struct point* points[], struct cluster* clusters[]) {