定义使用数组变量的大小 [英] Defining the size of array using variable

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

问题描述

在C语言中,这合法吗?

Is this valid in C language?

#include <stdio.h>
int main()
{
  int i = 5;
  int a[i];     // Compiler doesn't give error here. Why?
  printf("%d",sizeof(a));  //prints 5 * 4 =20. 4 is the size of integer datatype.
  return 0;
}

编译器不会在声明中给出错误 int类型的[I]; 。我是不是一个常量,那么它怎么能编译成功?难道是因为我使用gcc编译器?它是允许C ++?

Compiler doesn't give error at the statement int a[i];. i isn't a constant then how can it compile successfully? Is it because I am using gcc compiler? Is it allowed in C++?

推荐答案

是的,这是因为 C99 有效,和被称为可变长度数组(VLA)。换句话说,它已经在官方语言标准,大约14年。

Yes, this is valid as of C99, and is called a variable-length array (VLA). In other words, it has been in an official language standard for around 14 years.

不,这不是在C ++无效,看到这个问题了解详情。

No, it's not valid in C++, see this question for details.

另外请注意,的sizeof 是不是一个功能,这样就可以的printf写成(%祖\\ n,sizeof的一); 也使用了为size_t 值正确的格式说明。

Also note that sizeof is not a function, so that can be written as printf("%zu\n", sizeof a); which also uses the proper format specifier for a size_t value.

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

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