格式化代码以访问结构类型的数组索引

Formatting code to access array index of type struct

我在 C 中有以下代码:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    typedef struct sample { 
        int num;        
    } abc;

    typedef struct exmp{        
        abc *n1;        
    } ccc;

    abc *foo;
    foo = (abc*)malloc(sizeof(foo));
    ccc tmp;
    tmp.n1 = foo;

    ccc stack[10];

    stack[0] = tmp;
    printf("address of tmp is %p\n",&tmp);
    // need to print address contained in stack[0]

    return 0;
}

在上面的代码中,我想检查 stack[0] 的地址是否与 tmp 的地址相同。当我打印出 tmp 的地址时,如何在 stack[0] 打印地址?

很简单,就这样做

printf("address of tmp is %p and address of stack[0] %p\n",
    (void *)&tmp, (void *)&stack[0]);

实际上这会起作用

printf("address of tmp is %p and address of stack[0] %p\n", 
    (void *)&tmp, (void *)stack);

此外,Do not cast malloc(),并始终检查返回值是否不是 NULL,即它是一个有效的指针。