Reputation: 89
I have to create a function that initializes k cluster choosing the starting center based on the distance between the point. This is the code i wrote:
int *inizialize_centroids(int *p_dataset, int d, int k, int **p_discard_set) {
int* centroids = (int*) malloc(k*((2*d)+1)*sizeof(int)), *point_to_compare = (int*) malloc(d*sizeof(int)),
*cluster_point = (int*) malloc(d*sizeof(int));
float* distance = (float*) malloc(2*k*sizeof(float));
if(centroids == NULL || point_to_compare == NULL || cluster_point == NULL || distance == NULL){
printf("Something went wrong in inizialize_centroids(), memory allocation failed! (row 94/95)");
exit(1);
}
centroids[0]=1;
for(int i = 1; i < d; i++){
centroids[i] = p_dataset[i];
centroids[i+d] = pow(p_dataset[i],2);
}
*p_discard_set[0] = 1;
*p_discard_set[1] = p_dataset[0];
memcpy(cluster_point, &p_dataset[0], (d + 1)*sizeof(int));
int j;
int i = 1;
int t;
while (i < k){
j = 0;
while(j < 2*CHUNK ){
memcpy(point_to_compare, &p_dataset[j/2 * (d + 1)], (d + 1) * sizeof(int));
distance[j] = (float) point_to_compare[0];
j++;
distance[j] = compare(cluster_point, point_to_compare, i, d);
j++;
}
int id = (int) distance[0];
float max = distance[1];
j = 0;
while (j < 2* CHUNK){
if(distance[j+1] > max){
max = distance[j+1];
id = distance[j];
}
j+=2;
}
i++;
*p_discard_set[0] = i;
*p_discard_set[i] = id; //HERE OCCURE THE PROBLEM
[....]
}
return centroids;
The problem is that, i can't assign
*p_discard_set[i] = id;
and i don't understand why it gives me "interrupted by signal 11: SIGSEGV"
This is how i use it in main:
int *discard_set = (int*) malloc((k + 1) * sizeof(int)), *compressed_set = (int*) malloc(sizeof(int)), *retained_set = (int*) malloc(sizeof(int));
// discard_set è così fatto: [n, id_1, ... , id_n]
if(discard_set == NULL || compressed_set == NULL || retained_set == NULL){
printf("Something went wrong in main(), memory allocation failed! (row 39)");
exit(1);
}
int* centroids = inizialize_centroids(dataset, d, k, &discard_set);
The stange thing is that i can do
*p_discard_set[0] = i;
and k > 2, so it isn't out of bound, I think.
Upvotes: 0
Views: 49
Reputation: 126546
The precedence of postfix operators in C is higher than prefix, so when you say
*p_discard_set[i] = ...
you actually get
*(p_discard_set[i]) = ...
and what you actually want is
(*p_discard_set)[i] = ...
so you need the explicit parentheses to make it work the way you are expecting.
Upvotes: 2