我是C的绝对新手所以这可能是一个愚蠢的问题,警告!
它的灵感来自于学习困难之路中的练习16的额外学分,如果有人想知道背景的话.
假设这些进口:
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
Run Code Online (Sandbox Code Playgroud)
给出一个像这样的简单结构:
struct Point {
int x;
int y;
};
Run Code Online (Sandbox Code Playgroud)
如果我在堆上创建它的实例:
struct Point *center = malloc(sizeof(Point));
assert(center != NULL);
center->x = 0;
center->y = 0;
Run Code Online (Sandbox Code Playgroud)
然后我知道我可以在内存中打印结构的位置,如下所示:
printf("Location: %p\n", (void*)center);
Run Code Online (Sandbox Code Playgroud)
但是如果我在堆栈上创建它呢?
struct Point offCenter = { 1, 1 };
Run Code Online (Sandbox Code Playgroud)
位于堆栈中的值仍然在内存中的某个位置.那么我如何获得这些信息呢?我是否需要创建指向我的新on-the-stack-struct的指针然后使用它?
编辑:哎呀,猜测这有点显而易见.感谢Daniel和Clifford!为了完整性,这里的打印示例使用&:
printf("Location: %p\n", (void*)¢er);
Run Code Online (Sandbox Code Playgroud)
Cli*_*ord 11
用"address-of"运算符一元&.
struct Point offCenter = { 1, 1 };
struct Point* offCentreAddress = &offCentre ;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20873 次 |
| 最近记录: |