c++ - 编译器错误 :falied to determine size of array size identifier

标签 c++ arrays compiler-errors

下面是合并两个数组的代码,在第 5-6 行为什么一个编译正常而另一个显示错误“Intializer 无法确定结果的大小”

 void Merge(int first[],int second[],int f_length,int s_length){
     int total_length=f_length+s_length;
     int f_count=0;
     int s_count=0;
     **int result[total_length]**;//this is working fine
     *int result[]=new int[total_length]*;//Generating compiler error
     for(int i=0;i<total_length;i++){
            if(first[f_count]<second[s_count] && f_count<f_length)
                result[i]=first[f_count++];
            else
                 result[i]=second[s_count++];
             }
     for(int i=0;i<total_length;i++)
             cout<<result[i]<<endl;
     }

最佳答案

在 C++ 中,定义一个数组要求它的大小在编译时是一个常量表达式。所以这个定义

 int result[total_length];

无效,因为 total_length 不是常量表达式。

如果你指的是下面这行

int result[]=new int[total_length];

那么正确的语法是

int *result = new int[total_length];

编译器报告错误,因为它无法根据表达式确定数组的大小

new int[total_length]

由于使用了无效的语法结构。

除此之外,您的功能无效。您不检查 s_count 是否超过 s_length。即使这个无效条件

if(first[f_count]<second[s_count] && f_count<f_length)

至少应该写成

if ( f_count<f_length && first[f_count]<second[s_count] )

因为您不能取消引用指向数组最后一个元素之外的指针。那就是首先您取消引用指针 first[f_count]<second[s_count]并且只有在你检查它是否是数组中最后一个元素之后的元素之后 f_count<f_length

关于c++ - 编译器错误 :falied to determine size of array size identifier,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21884028/

相关文章:

c++ - VST C++ 嵌套类 - 构造和包含

c++ - Undefined Behavior 和 Ill-formed 之间的区别,不需要诊断消息

java - “找不到符号”或“无法解析符号”错误是什么意思?

java - 嵌套的异常是java.lang.VerifyError : Bad return type + getProfiler()Lcom/orientechnologies/common/profiler/OProfiler; @4: areturn

javascript - 将对象数组减少为键值对映射,保留值数组中的重复条目

c++ - 未在此范围内声明的函数和变量(c++)

c++ - 我可以从 C 或 C++ 外部控制 Chrome 扩展程序吗?

c++ - 未知的动态类型转换

c - 标识 : Is that a string?

arrays - Postgres GROUP BY 整数数组