关于C语言中定义数组大小的问题(最多能定义多少)

Python013

关于C语言中定义数组大小的问题(最多能定义多少),第1张

在MSDN中的array declarations有如下描述:

The type of integer required to hold the maximum size of an array is the size of size_t. Defined in the header file STDDEF.H, size_t is an unsigned int with the range 0x00000000 to 0x7CFFFFFF.

也就是说,只要硬件条件许可的条件下,数组的大小可以为0x7CFFFFFF(2G BYTE)。

数组所占空间为:count*sizeof(TYPE) , count是数组元素的个数,sizeof(TYPE) 是一个元素所占空间字节数。

如果定义数组空间超出2G,VC编译会报错:fatal error C1126: '2G' : automatic allocation exceeds 。。。

因此,当实际编程确实需要使用更大的数组时,则要采用动态定义方式(new malloc等)。

动态分配的数组可以自定义数组的长度,示例如下:

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

int main()

{

printf("输入要分配的内存大小:")

int size

scanf("%d", &size)  //输入自定义的数组长度

int *pstart = (int *)malloc(sizeof(int) *size)

if (pstart==0) {

printf("不能分配内存\n")

return 0

}

memset(pstart, 0x00, sizeof(int) * size)

int inx

for (inx=0 inx!=size ++inx) pstart[inx] = inx

for (inx=0 inx!=size ++inx) printf("%d\t", pstart[inx])

printf("\n")

return 0

}

有几种方法:1)可以定义一个足够大的数组,保证够用就好。2)使用链表结构,用一个申请一个元素的空间3)用malloc先申请一定的空间作为数组的空间,等到不够用的时候,再重新malloc一个更大的空间,将旧的那个空间里的数据拷贝过来,作为数组的新的空间,然后free掉旧的那个空间即可。