在变长数组的sizeof行为(仅C) [英] Behavior of sizeof on variable length arrays (C only)

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

问题描述

我的问题是如何准确的sizeof()时的行为传递的参数是一个<击>动态数组可变长度的数组。

My question is how exactly sizeof() behaves when passed argument is a dynamic array variable length array.

让我们来看一个例子:

int fun(int num_of_chars)
{
    char name_arr[num_of_chars] = {0};

    /* Do something*/

    return sizeof(name_arr);
}

在本实施例中显而易见的是返回值不是一个编译时间常数。由于大小取决于 num_of_chars 的运行时间值。

In this example it is obvious that return value is not a compile time constant. Because the size depends on run time value of num_of_chars.

从C99标准引号(6.5.3.4):

A quote from C99 standard (6.5.3.4):

的sizeof 运营商产生的操作数的大小(以字节为单位),这可能是一个
      前pression或类型的括号名称。尺寸是从确定
      操作数的值。结果是整数。如果操作数的类型是一个
      变长数组类型,操作数计算;否则,操作数是
      没有评估,结果是整型常量。

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.

我可以理解什么[....操作数进行评估......]是,当参数通过了的sizeof()是<击>动态数组变长数组, 的sizeof()'的行为就像一个功能,而不是作为一个经营者

What I can understand from [....the operand is evaluated....] is that when the argument passed for sizeof() is a dynamic array variable length array, sizeof() 'behaves like' a function and not as an operator.

我的理解是正确的?

推荐答案

它仍然表现为一个运营商。演员也是运营商,也计算它的说法也是如此 * &安培; 。作为一个经营者是一个语法范畴。这并没有改变。

It still behaves as an operator. Cast is also operator and also evaluates it's argument and so does * or & . Being an operator is a syntactic category. That does not change.

重要的区别在于,它表现为前pression 而在其他情况下,它表现为

The important distinction is that it behaves as expression while in other cases it behaves as constant.

更新:我下面的评论,我不明白为什么评价,使区别,但现在我意识到还有的两个的你可以写sizeof的可变长度数组的方式。要么你可以通过声明为变量lenght数组变量:

Update: I commented below that I don't see why the evaluation makes difference, but now I realized there are two ways you can write sizeof with variable length array. Either you can pass variable declared as variable lenght array:

int a[x];
sizeof(a)

在这种情况下,评估 A 确实没什么区别。但你也可以使用的键入的作为参数,这将是

in which case evaluating a indeed makes no difference. But you can also use a type as the argument, which would be

sizeof(int[x])

在这种情况下,结果是 X *的sizeof(INT) X 必须进行评估。我想就是为什么规范中提到的。

and in this case the result is x * sizeof(int) and x must be evaluated. Which I suppose is why the specification mentions it.

这篇关于在变长数组的sizeof行为(仅C)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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