是否有在C数组的最大尺寸有限制吗? [英] Is there any limitation on the maximum size of array in c?

查看:108
本文介绍了是否有在C数组的最大尺寸有限制吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/3049934/c-programming-why-does-this-large-array-declaration-produce-a-segmentation-faul\">C编程,为什么这大阵声明产生分段错误?


我读的C语言的形象,但我不能这样做,因为我的程序调试,我发现,这是由于数组的大小... ...后停止之间在有上最大规模的任何限制数组?
如果我声明大小的数组1400X1400一切工作正常,但如果我定义尺寸1600X1400我的程序的阵列停止工作......为什么如此...有没有通过数组大小的编译器或操作系统施加的任何限制?如果是的话是什么在C此解决方案。

  unsigned char型IDATA [1400] [1400] //工作正常
    unsigned char型IDATA [1600] [1400] //不工作


解决方案

我猜测 IDATA 是一个局部变量。问题是,局部变量存储在堆栈(技术上自动存储)上,堆栈比6400兆字节你想分配上要小得多。分配其上的存储导致堆栈溢出。

尝试

  unsigned char型** IDATA =新的无符号的char * [DIM1]的for(int i = 0; I&LT; D​​IM1 ++ I)
    IDATA [I] =新的无符号的char [DIM2]// 要么无符号字符(* IDATA)[DIM2] =新的char [DIM1] [DIM2];

要在自由存储分配它,你不应该有问题。

编辑:

我刚刚看了一下标签,并没有看到你只谈论C.如果是这样,你可以做同样的事情,但使用的malloc 而不是<$的C $ C>新:

  unsigned char型** IDATA =的malloc(sizeof的(无符号字符*)* DIM1);对于(i = 0; I&LT; D​​IM1 ++ I)
    IDATA [I] =的malloc(DIM2);// 要么无符号字符(* IDATA)[DIM2] =的malloc(DIM1 DIM2 *);

和不要忘了免费(或删除[] 对于C ++),你分配的​​内存,以避免内存泄漏。

Possible Duplicate:
C programming, why does this large array declaration produce a segmentation fault?

I am reading an image in c language but i am unable to do so as my program is stopping in between... after debugging i found that it is due to array size... is there any restriction on maximum size of array? if i declare array of size 1400X1400 everything works fine but if i define array of size 1600X1400 my program stops working... why it is so... is there any limit imposed by compiler or OS on array size? and if so what is solution for this in c.

    unsigned char idata[1400][1400]; //working fine
    unsigned char idata[1600][1400]; //not working

解决方案

I am guessing that idata is a local variable. The problem is that local variables are stored on the stack (technically "automatic storage"), and the stack is much smaller than the 6400 megabytes you're trying to allocate on it. Allocating that much storage on it causes a stack overflow.

Try

unsigned char** idata = new unsigned char*[DIM1];

for (int i = 0; i < DIM1; ++i)
    idata[i] = new unsigned char[DIM2];

// or

unsigned char (*idata)[DIM2] = new char[DIM1][DIM2];

To allocate it in the free store and you shouldn't have a problem.

EDIT:

I just looked at the tags and didn't see you were only talking about C. If so, you can do the same thing but use malloc instead of new:

unsigned char** idata = malloc(sizeof(unsigned char*) * DIM1);

for (i = 0; i < DIM1; ++i)
    idata[i] = malloc(DIM2);

// or

unsigned char (*idata)[DIM2] = malloc(DIM1 * DIM2);

And don't forget to free (or delete[] for C++) the memory you allocate to avoid memory leaks.

这篇关于是否有在C数组的最大尺寸有限制吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆