c语言中使用常量定义数组元素个数为什么只能用#define?

#include<stdio.h>
int main(void)
{
const int SIZE = 8;
int by_two[SIZE];
这样写编译器就会报错
error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
error C2133: 'by_two' : unknown sizeror C2057: expected constant expression
说我没有没有定义SIZE常量,但如果改成这样
#include<stdio.h>
#define SIZE 8
int main(void)
{
int by_two[SIZE];
就可以正常运行,这是为什么啊?这两种定义常量的方式有什么区别吗?求大神指教!
另外我用的是vc++6.0 系统是win8.1 64位 谢谢了O(∩_∩)O~

C语言中数组的维数表示数组中元素的个数,在常规数组中维数是必须要指明的,如果没有指明,则必须在初始化列表中给定初始值,编译器通过初始化列表来确定数组的维数。
int a[] = {1,2,3,4};
上面的代码虽然没有指明数组的维数,但是编译知道数组a的维数是4(只有4个元素)。

要实现用变量定义数组的元素个数即维数,可以使用malloc()和free()来进行动态内存分配 。下面是一个使用动态内存的示例:
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int size;
printf("输入建立元素的个数:");
scanf("%d",&size);
int *p = (int *)malloc(sizeof(int) * size);
if (p == 0) {
printf("不能分配内存\n");
return 0;
}

//初始化内存
memset(p, 0x00, sizeof(int) * size);
//释放内存
free(p);
return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-08-19
int by_two[SIZE]会在编译阶段初始化,SIZE的值是在运行阶段取到的,编译阶段是没有取到值,所以错了。
define SIZE 8是在编译阶段直接替换,int by_two[SIZE]相当于int by_two[8],所以说可以的。