变量作为数组大小 [英] variable as an array size

查看:48
本文介绍了变量作为数组大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我想知道你对这段代码的看法:


#include< iostream>


int main()

{

int size;

std :: cin>>尺寸;

int array [size];


std :: cout<< sizeof(int)<<" "<< sizeof(array);

返回0;

}


是否合法(根据到C / C ++标准)?

几天前我会说它不是,只有常量表达式可以用
来指定数组的大小,但现在我不确定:)

的原因是gcc 3.4.4编译时没有错误和警告。

程序打印的结果是正确:


sizeof(arr)= size * sizeof(int)


PS

MS Visual C ++ 7.1不编译此代码。它给出了以下错误:

main.cpp(7):错误C2057:预期的常量表达式

main.cpp(7):错误C2466:无法分配数组常量大小0

main.cpp(7):错误C2133:''array'':未知大小

main.cpp(9):错误C2070:''int []'':非法sizeof操作数

Hi,

I''m wondering what you think about this piece of code:

#include<iostream>

int main()
{
int size;
std::cin >> size;
int array[size];

std::cout<<sizeof(int)<<" "<<sizeof(array);
return 0;
}

Is it legal or not (according to C/C++ standard)?
A couple of days ago I would say it is not, only constant expression can
be used to specify the size, of the array, but now I''m not sure :) The
reason is that gcc 3.4.4 compiles at with no errors and warnings.
And the result printed by the program is correct:

sizeof(arr) = size * sizeof(int)

P.S.
MS Visual C++ 7.1 does not compile this code. It gives the following errors:
main.cpp(7) : error C2057: expected constant expression
main.cpp(7) : error C2466: cannot allocate an array of constant size 0
main.cpp(7) : error C2133: ''array'' : unknown size
main.cpp(9) : error C2070: ''int []'': illegal sizeof operand

推荐答案

HappyHippy写道:
HappyHippy wrote:



我想知道你对这段代码的看法:


它使用gcc扩展名。

几天前我会说它不是,只有常量表达才能用来指定大小,

Hi,

I''m wondering what you think about this piece of code:

it uses an gcc extension.
A couple of days ago I would say it is not, only constant expression can
be used to specify the size,




至于现在,你是对的。
< br $>
-

Karl Heinz Buchegger
kb ***** *@gascad.at


我真的不喜欢这种不必要的扩展。我试图打开

一些标志来迫使gcc将其视为错误。但到目前为止我得到的全部

是一个警告 - 有点愚蠢。有没有办法将它升级为

错误?谢谢。


[nan @ xxx test]
I really don''t like this unnecessary extension. I tried to turn on
some flags to force gcc to treat it as an error. But all I got so far
is an warning with -pedantic. Is there any way to escalate it to
error? Thanks.

[nan@xxx test]


cat ary.c

int main()

{

int size;

int array [size];

返回0;

}


[nan @ xxx test]
cat ary.c
int main()
{
int size;
int array[size];
return 0;
}

[nan@xxx test]


这篇关于变量作为数组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆