为什么这个C程序不能编译?这有什么问题?
我试过它wxDevC++和Turbo C++ 3.0.
#include<stdio.h>
#include<conio.h>
const int SIZE = 5;
int main(int argc, char ** argv)
{
char array[SIZE] = {'A', 'B', 'C', 'D', 'E'};
printf("Array elements are,\n");
int i=0;
for(i=0 ; i<SIZE ; ++i)
{
printf("%c ", array[i]);
}
getch();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
两个编译器上的错误消息类似.
f:\_Source-Codes\main.c In function `main':
8 f:\_Source-Codes\main.c variable-sized object may not be initialized
Run Code Online (Sandbox Code Playgroud)
如果编译器将其视为'.c'文件,则int i声明需要在任何可执行行之前,特别是在之前printf.
编辑,现在您显示错误消息:
SIZE编译main时,编译器不会将其视为常量.你可以#define SIZE 5用作解决方法.
根据K&R 2nd Ed.:
"目的
const是宣布可能放在只读内存中的对象.除了它应该诊断显式尝试更改const 对象之外,编译器可能会忽略[const]限定符".
因此,宣布const int SIZE = 5不会使SIZE一个常数表达式,这是一个数组尺寸说明要求什么.
尝试更换
const int SIZE = 5;
Run Code Online (Sandbox Code Playgroud)
同
#define SIZE 5
Run Code Online (Sandbox Code Playgroud)
大多数C编译器不允许声明其大小包含在变量中的静态数组(即数组大小是在运行时确定的).