下面是合并两个数组的代码,在第 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/