我怎样才能获得在C结构的地址? [英] How can I get the address of a struct in C?

查看:76
本文介绍了我怎样才能获得在C结构的地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个绝对的新手到C所以这可能是一个愚蠢的问题,警示!

它是由额外的信贷部分的启发在学习C坚硬方式锻炼16 的,如果有人想了解一下背景。

假设这些进口:

 的#include<&stdio.h中GT;
#包括LT&;&ASSERT.H GT;
#包括LT&;&stdlib.h中GT;

和给出一个简单的结构是这样的:

 结构点{
    INT X;
    诠释Ÿ;
};

如果我在堆上创建它的一个实例:

 结构*点=中心的malloc(sizeof运算(点));
断言(中心!= NULL);
中心 - > X = 0;
中心 - > Y = 0;

我就知道我可以打印结构的位置,在内存中是这样的:

 的printf(位置:%P \\ N(无效*)中心);

但如果我在栈上创建了吗?

 结构点offCenter = {1,1};

坐在堆

值在内存中还是有位置的某处。那么,如何在我的信息得到什么?我需要创建一个指向我的新的On-The-堆栈结构,然后用它?

编辑:哎呦,你猜这是一个有点明显的一种。感谢丹尼尔和祈福!为了完整这里使用&放打印的例子;

 的printf(位置:%P \\ N(无效*)及中心);


解决方案

通过操作一元地址的&放大器;

 结构点offCenter = {1,1};
结构点* offCentreAddress =安培; offCentre;

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);

解决方案

With the "address-of" operator unary &.

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

这篇关于我怎样才能获得在C结构的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆