I'm a software engineer getting my master's degree and I'm coding a program in C that implements the Lloyd Algorithm. However, I'm stuck in this segmentation fault 11.. I'm working with big numbers, that's why it's breaking but I've tried to render it as much as possible and I'm still getting this error.
These are the structs implemented:
struct point{
float x;
float y;
};
struct cluster{
float x;
float y;
float* points;
};
This is my code:
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]);
}
}
In the main file:
#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: %f\n",clusters[i]->x);
printf("Coordinate Y: %f\n\n",clusters[i]->y);
}*/
free_structs(N,K,points,clusters);
return 0;
}
Can you give me a hand, please?