You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言编译错误:‘arr’的存储大小不是常量,如何解决?

C语言编译错误:storage size of 'arr' isn't constant 原因及修复

错误信息

storage size of 'arr' isn't constant
int static arr[size];

原代码

#include<stdio.h>
int* func( int size );
void main (){
    int*res ;
    int len =5 ;
    res=func(len);
    for(int i=0 ;i<len;++i){
        printf("The Element %d is \n",i,*(res+i));
    }
}
int* func( int size ){
    
    int static arr[size];
    for(int i=0 ;i<size;++i){
        printf("Enter %d \n",i);
        scanf("%d",&arr[i]);
    }
    return arr ;
}

错误原因

  • C语言标准规定,静态数组的大小必须是编译期常量,不能是运行时才确定的变量(比如传入的size参数)。静态存储区的内存在程序启动时就分配完成,编译器需要在编译阶段明确知道数组的具体大小,无法根据运行时的变量值动态调整。
  • 原代码还有一处小问题:printf语句缺少一个格式占位符,"The Element %d is \n"应该对应两个参数,但只写了一个%d,会导致输出异常。

修复方案

方式一:动态内存分配(推荐)

使用malloc在堆上分配内存,支持根据运行时的size动态确定数组大小,注意使用完后要释放内存避免泄漏:

#include<stdio.h>
#include<stdlib.h>

int* func( int size );
int main (){
    int* res ;
    int len =5 ;
    res=func(len);
    for(int i=0 ;i<len;++i){
        printf("The Element %d is %d\n",i,*(res+i));
    }
    free(res);
    return 0;
}
int* func( int size ){
    int *arr = malloc(size * sizeof(int));
    if(arr == NULL){
        printf("内存分配失败\n");
        exit(1);
    }
    for(int i=0 ;i<size;++i){
        printf("Enter %d \n",i);
        scanf("%d",&arr[i]);
    }
    return arr ;
}

方式二:使用变长数组(VLA,C99及以上标准支持)

如果编译器支持C99标准,可以使用栈上的变长数组,但注意不能返回变长数组的地址(函数返回后栈帧会被销毁),需要调整逻辑让调用者提供数组:

#include<stdio.h>

void func( int size, int arr[] );
int main (){
    int len =5 ;
    int arr[len];
    func(len, arr);
    for(int i=0 ;i<len;++i){
        printf("The Element %d is %d\n",i,arr[i]);
    }
    return 0;
}
void func( int size, int arr[] ){
    for(int i=0 ;i<size;++i){
        printf("Enter %d \n",i);
        scanf("%d",&arr[i]);
    }
}

内容的提问来源于stack exchange,提问作者khairy nagy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 00:43:27