是“数组"吗?和“& array [0]"完全可以互换? [英] Are "array" and "&array[0]" completely interchangeable?

查看:90
本文介绍了是“数组"吗?和“& array [0]"完全可以互换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是的,它曾经被问过很多次,但是我想知道哪个更合适?

Yes, it has been asked before, many times, but I wanna know which one is more advisable?

typedef struct {
    int a;
    int addr[8];
} usr_command;

usr_command* p_usr_command;

int foo(int* parameter)
{}

那么哪一个更不容易出现问题呢?

So which one is less prone to be problematic?

foo(p_usr_command->addr);

foo(&p_usr_command->addr[0]);

?

推荐答案

这种 情况下(传递数组名称将数组中第一个对象的地址作为函数参数传递给),这两个代码段都是等效的.

In this case ( passing an array name vs. passing the address of the first object in the array as function argument), both the snippets are equivalent.

引用C11,第6.3.2.1章,左值,数组和函数指示符(强调我的)

Quoting C11, chapter §6.3.2.1, Lvalues, arrays, and function designators (emphasis mine)

除了它是sizeof运算符,_Alignof运算符或 一元&运算符,或者是用于初始化数组的字符串文字,具有 类型类型数组" 转换为类型为类型指针" 的表达式 数组对象的初始元素,而不是左值. [....]

Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. [....]

但是,通常它们是 不同 .

However, in general, they are not the same.

  • array是类型为int [8]
  • 数组
  • &(array[0])指针,键入int *
  • array is an array of type int [8]
  • &(array[0]) is a pointer, type int *

EOF在其评论中已经建议,尝试将两个变体都传递给sizeof运算符,然后检查结果以获取动手操作输出.

As already suggested by EOF in his comment, try passing both variants to the sizeof operator and check the result to get the hands-on output.

这篇关于是“数组"吗?和“& array [0]"完全可以互换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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