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

2020-03-17 04:09发布

问题:

I'm an absolute newbie to C so this may be a dumb question, warning!

It's inspired by the extra credit section of Exercise 16 in Learn C the Hard Way, if anyone is wondering about context.

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?

EDIT: Whoops, guess that was a bit of an obvious one. Thanks to Daniel and Clifford! For completeness here's the print example using &:

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

回答1:

With the "address-of" operator unary &.

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


标签: c memory