简体   繁体   English

如何在C中获取结构的地址?

[英]How can I get the address of a struct in C?

I'm an absolute newbie to C so this may be a dumb question, warning! 我是C的绝对新手所以这可能是一个愚蠢的问题,警告!

It's inspired by the extra credit section of Exercise 16 in Learn C the Hard Way, if anyone is wondering about context. 它的灵感来自于学习困难之路中的练习16的额外学分,如果有人想知道背景的话。

Assuming these imports: 假设这些进口:

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

And given a simple struct like this: 给出一个像这样的简单结构:

struct Point {
    int x;
    int y;
};

If I create an instance of it on the heap: 如果我在堆上创建它的实例:

struct Point *center = malloc(sizeof(Point));
assert(center != NULL);
center->x = 0;
center->y = 0;

Then I know I can print the location of the struct in memory like this: 然后我知道我可以在内存中打印结构的位置,如下所示:

printf("Location: %p\n", (void*)center);

But what if I create it on the stack? 但是如果我在堆栈上创建它呢?

struct Point offCenter = { 1, 1 };

Values sitting in the stack still have a location in memory somewhere. 位于堆栈中的值仍然在内存中的某个位置。 So how do I get at that information? 那么我如何获得这些信息呢? Do I need to create a pointer to my new on-the-stack-struct and then use that? 我是否需要创建指向我的新on-the-stack-struct的指针然后使用它?

EDIT: Whoops, guess that was a bit of an obvious one. 编辑:哎呀,猜测这有点显而易见。 Thanks to Daniel and Clifford! 感谢Daniel和Clifford! For completeness here's the print example using & : 为了完整性,这里是使用&的打印示例:

printf("Location: %p\n", (void*)&center);

With the "address-of" operator unary & . 随着“地址”运算符一元&

struct Point offCenter = { 1, 1 };
struct Point* offCentreAddress = &offCentre ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM