error: lvalue required as unary ‘&’ operand, I've seen solutions but I can't relate them to my query

error: lvalue required as unary ‘&’ operand, I've seen solutions but I can't relate them to my query

我可以通过将 &(name+0) 替换为 &name[0] 或只是 name 轻松消除此错误,但为什么我会收到此错误?

#include<stdio.h>
#include<string.h>

void print(char *c)
{
   while(*c != '[=10=]')
   {
       printf("%c",*c);
       c++;
   } 
   printf("\n");
}
int main(void)
{
    char name[]="Hello World!";
    print(&(name+0)); //ERROR here
    return 0;
}

使用

print(&(name+0)); //ERROR here

好像是误会了。

首先要做的是 - 为什么是句法错误?

(name + 0) 不计算为 左值 。因此,您不能获取该表达式值的地址。

判断某物是否为 lvalue 的一个简单方法是问问自己:我可以在赋值运算符的 LHS 上使用它吗?在你的情况下,你必须问:我可以使用

(name + 0) = <something>;

答案是"no"。

如果要将name的第一个元素的地址传递给print,可以使用两种方法。

print(&(name[0]));  // Explicitly get the first element's address.
print(name);        // The array decays to the address of the first element.

&(name+0) 不等同于 &name[0]&name[0]&(*(name + 0)) 相同。请注意 间接 ,当您使用下标运算符时,它与偏移指针 和取消引用 相同。

引用6.3.2.1第1小节中的C11标准:

An lvalue is an expression (with an object type other than void) that potentially designates an object; if an lvalue does not designate an object when it is evaluated, the behavior is undefined. When an object is said to have a particular type, the type is specified by the lvalue used to designate the object.

在本例中,您得到了表达式 (name + 0)。虽然 name 本身指定一个对象,因此是一个左值,但该表达式中的加法结果不指定一个对象,而是一个值,并且不是左值,因此不符合一元 & 运算符。