java动态分配空间,为动态数组分配大空间

我们编写了一个程序,它将逗号分隔的整数值读入数组,并尝试使用并行结构处理它们 . 通过这样做,我们发现动态数组的最大大小存在固定限制,通常通过将大小加倍来动态分配 . 然而,对于具有超过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开始) . 这虽然没有影响结果,或者仍然不起作用 . 无论如何,谢谢你指出错误!我还将包含的代码减少到相关部分 .

我不能真正理解它应该以这种方式工作,但事实并非如此,所以它可能只是我们忽略的一个小错误 . 提前致谢 .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值