我们编写了一个程序,它将逗号分隔的整数值读入数组,并尝试使用并行结构处理它们 . 通过这样做,我们发现动态数组的最大大小存在固定限制,通常通过将大小加倍来动态分配 . 然而,对于具有超过5000个值的数据集,我们不能再将其加倍 .
我现在有点困惑,因为从技术上讲,我们做了所有其他帖子指出我们应该做的事情(使用realloc,不要使用堆栈而是使用堆) .
请注意,它适用于任何小于或等于5000值的文件 . 我们也尝试使用realloc,但结果相同 .
#include
#include
#include
// compile with gcc filename -lpthread -lm -Wall -Wextra -o test
int reader(int ** array, char * name) {
FILE *fp;
int data,row,col,count,inc;
int capacity=10;
char ch;
fp=fopen(name,"r");
row=col=count=0;
while(EOF!=(inc=fscanf(fp,"%d%c", &data, &ch)) && inc == 2){
if(capacity==count)
// this is the alternative with realloc we tried. Still the same issue.
//*array=malloc(sizeof(int)*(capacity*=2));
*array = realloc(*array, sizeof(int)*(capacity*=2));
(*array)[count++] = data;
//printf("%d ", data);
if(ch == '\n'){
break;
} else if(ch != ','){
fprintf(stderr, "format error of different separator(%c) of Row at %d \n", ch, row);
break;
}
}
// close file stream
fclose(fp);
//*array=malloc( sizeof(int)*count);
*array = realloc(*array, sizeof(int)*count);
return count;
}
int main(){
int cores = 8;
pthread_t p[cores];
int *array;
int i = 0;
array=malloc(sizeof(int)*10);
// read the file
int length = reader(&array, "data_2.txt");
// clean up and exit
free(array);
return 0;
}
编辑:我包括我们尝试的realloc命令,并将值更改回原始测试值(从10开始) . 这虽然没有影响结果,或者仍然不起作用 . 无论如何,谢谢你指出错误!我还将包含的代码减少到相关部分 .
我不能真正理解它应该以这种方式工作,但事实并非如此,所以它可能只是我们忽略的一个小错误 . 提前致谢 .