我在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 %pn",&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] %pn",
(void *)&tmp, (void *)&stack[0]);
实际上,这将工作
printf("address of tmp is %p and address of stack[0] %pn",
(void *)&tmp, (void *)stack);
此外,不要强制转换malloc()
,并始终检查返回的值是否不是NULL
,即它是否是有效的指针。