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

时间:2015-02-14 08:03:58

标签: c pointers

我在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]打印地址?

1 个答案:

答案 0 :(得分:5)

这很简单,只需这样做

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,即它是否为有效指针。