I have a struct with arrays that size are not specified.
struct KMData{
int ndata;
int dim;
float **features;
int *assigns;
int *labels;
int nlabels;
};
like this.
In my function below, I try to malloc the memory for features and labels depending on the size of the given file, but it seems like it is not mallocing the size of the data I specified.
struct KMData kmdata_load(char *datafile) {
ssize_t tokens;
ssize_t lines;
filestats(datafile, &tokens, &lines);
struct KMData *data = malloc(sizeof(struct KMData) + (lines * sizeof(int)) + ((tokens - (2*lines)) * sizeof(float)));
printf("tokens: %zd, lines: %zd\n", tokens, lines);
data->labels = malloc(lines * sizeof(int));
data->features = malloc((tokens - (2*lines)) * sizeof(float));
ssize_t f_size = sizeof(*(data->features));
printf("size of features: %zd\n", f_size);
FILE *fin = fopen(datafile, "r");
char line[3150];
int i = 0;
while (fgets(line, 3150, fin)) {
data->ndata++;
char *token = strtok(line, " \t");
data->labels[data->ndata-1] = atoi(token);
float feats[(tokens/lines)-2];
int f = 0;
token = strtok(NULL, " \t");
while ((token = strtok(NULL, " \t"))) {
feats[f] = atof(token);
data->features[data->ndata-1][f] = atof(token);
if(i==0){
printf("token %d: %f\n", f, data->features[data->ndata-1][f]);
}
f++;
}
i++;
ssize_t size = sizeof(feats)/sizeof(float);
}
fclose(fin);
return *data;
}
int main(int argc, char* argv[]){
struct KMData data = kmdata_load(argv[1]);
}
Anything that I missed here?
When I print out the size of features, it gives 8, which is way smaller than what I am expecting.
after reading comments and answers, I tried doing
struct KMData *data = malloc(sizeof(struct KMData));
data->labels = malloc(lines * sizeof(int));
then
data->labels[data->ndata-1] = atoi(token);
but it gives me segmentation fault, so am I still not allocating the array correctly?