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

标签 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] 处打印地址?

最佳答案

很简单,就这么做

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,即它是一个有效的指针。

关于c - 格式化代码以访问结构类型的数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28513705/

相关文章:

c - 如何使用 WinPCap 获取以太网标签

c - ansi c 中可变数量的参数(不同类型)

c - 如何在没有 Visual Studio 的情况下为 Windows 编写内核驱动程序?

c - 如何获取基栈指针的地址

c - 查找指向数组的指针的大小

c++ - 将指向函数的指针分配给指向函数对象的指针的地址

C libpcap API 提取 DNS 查询

c - C 中的堆栈实现产生令人困惑的结果

c - 返回 main 时内存分配不是 "hold"

c - 在变量参数函数中使用字符串指针