复合文字如何在此代码中工作?

cpx*_*cpx 1 c gcc c99 compound-literals

我有以下代码,其中我写了两个函数.两者都意味着产生相同的输出.但是g()具有循环的函数产生的输出与我预期的不同,如下所示.

#include <stdio.h>

struct S { int i; };

void f(void)
{
    struct S *p;

    int i = 0;

    p = &((struct S) {i});
    printf("%p\n", p);

    i++;

    p = &((struct S) {i});
    printf("%p\n", p);
}

void g(void)
{
    struct S *p;

    for (int i = 0; i < 2; i++)
    {
        p = &((struct S) {i});
        printf("%p\n", p);
    }
}

int main()
{   
    printf("Calling function f()\n");
    f();

    printf("\nCalling function g()\n");
    g();
}
Run Code Online (Sandbox Code Playgroud)

输出:

Calling function f()
0023ff20
0023ff24

Calling function g()
0023ff24
0023ff24
Run Code Online (Sandbox Code Playgroud)

怎么来的地址p处于相同的情况下,g()当它叫什么名字?

Jan*_*rny 5

好吧,我不确切地知道你想要完成什么,但这里发生的是:

  • (struct S){i}C99中的表示法将在堆栈上创建新的数据结构
  • 此数据结构在创建它的范围的末尾自动销毁

所以在f()函数中你实际上在整个函数的范围内创建了两个不同的结构(即使你将它们的地址分配给同一个指针) - 因此有两个不同的地址.

void f(void)
{
    struct S *p;

    int i = 0;

    p = &((struct S) {i}); // <- first data structure, let's call it A
    printf("%p\n", p);     // <- address of the structure A printed

    i++;

    p = &((struct S) {i}); // <- second data structure, let's call it B
    printf("%p\n", p);     // <- address of the structure B printed
}                          // <- both A and B destroyed
Run Code Online (Sandbox Code Playgroud)

但是在g()函数中,它p是在块的内部块中创建和销毁的for,因此发生p在堆栈的相同位置一遍又一遍地分配,总是给出相同的地址.

void g(void)
{
    struct S *p;

    for (int i = 0; i < 2; i++)
    {
        p = &((struct S) {i}); // <- data structure A created
        printf("%p\n", p);     // <- data structure A's address printed
    }                          // <- data structure A destroyed
}
Run Code Online (Sandbox Code Playgroud)