C语言中使用变量作为数组长度的错误及解决方案
这段代码中出错的原因是C语言中的数组长度必须是一个常量值,不能使用变量作为数组长度。在这里,'total_samples'是一个变量,无法作为数组长度来定义'merged_labels'和'merged_scores'。
要解决这个问题,可以使用动态内存分配来创建合适大小的数组。可以使用'malloc'函数来分配内存,并在使用后使用'free'函数释放内存。
下面是修改后的代码示例:
int total_samples = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < num_samples[i]; j++) {
fprintf(merged_file, "%lf %lf\n", truelabels[i][j], pridictedvalues[i][j]);
total_samples++;
}
}
fclose(merged_file);
double* merged_labels = malloc(total_samples * sizeof(double));
double* merged_scores = malloc(total_samples * sizeof(double));
// 使用merged_labels和merged_scores进行操作
free(merged_labels);
free(merged_scores);
这里使用'malloc'函数为'merged_labels'和'merged_scores'分配了足够的内存空间,大小为'total_samples * sizeof(double)'。在使用完后,记得使用'free'函数释放内存。
原文地址: https://www.cveoy.top/t/topic/njYD 著作权归作者所有。请勿转载和采集!