在 C 中获取临时(复合文字)参数的地址

Taking address of temporary (compound literal) parameter in C

我无法想象这不是重复的,但我无法轻易找到答案,因为专门针对 C++ 的更复杂的场景似乎主导了讨论0 .

在C99中调用函数参数列表中构造的临时地址是否合法?

例如init_listinit_desig_init如下:

typedef struct {
  int x;
  int y;
} point_t;

int manhattan(point_t *p) {
  return p->x + p->y;
}

int init_list() {
  return manhattan(&(point_t){1, 2});
}

int init_desig_init() {
  return manhattan(&(point_t){.x = 1});
}

三巨头1 seem to compile it OK,但是我实际上找不到参考解释至少通过函数调用会延长临时的生命周期.


0 事实证明,根据下面 M.M 的回答,我的部分搜索问题是因为我正在寻找有关 temporaries 的信息,而此特定初始化构造的正确 C 术语是 compound literal.

1 我真的应该称它为 "the big cross-platform three",以尊重 MSVC,但实际上我只是指 "the C compilers godbolt supports".

(point_t){1, 2} 不是 "temporary"。它是一个复合文字。 (C++中相同的token序列有不同的含义,这两种语言不要混淆)

复合字面量是左值,因此在其上使用一元 & 运算符是合法的。存储期限由C11 6.5.2.5/5涵盖:

If the compound literal occurs outside the body of a function, the object has static storage duration; otherwise, it has automatic storage duration associated with the enclosing block.

所以这段代码是正确的,复合文字一直存在,直到声明它的函数结束。