c - 为什么 C 输出中的自引用结构为空
问题描述
我想在 C 中创建一个结构,并且我希望它只有一个组件作为它的地址。
换句话说,我只是创建了一个组件自引用结构:
#include <stdio.h>
#include <string.h>
struct Books {
struct Books *ptr; //* the only one component of this structure*//
};
int main( ) {
struct Books book1;
printf("%p\n", book1.ptr);
return 0;
}
此脚本的输出为 - nil。
我的问题是 - 为什么?该脚本在计算机内存中创建了一个物理条目,其中记录了一个组件 structbook1。
现在我想查看这个结构的地址(或者换句话说,我想查看这个单组件结构的内容)。
一旦它物理存在,为什么它会给我输出 nill ?
解决方案
如果您希望结构成员(或任何对象)具有特定值,则必须对其进行初始化或分配以具有该值。仅仅因为成员的类型是“指针struct Books
”并不意味着它指向 struct Books
它所在的位置或它具有任何其他特定值。
使用struct Books book1 = { &book1 };
.
此外,应该为%p
转换提供一个参数,因此请转换您传递的地址:。printf
void *
printf("%p\n", (void *) book1.ptr);
推荐阅读
- python - python函数中的正确方式提示'->'多个返回类型
- vuetify.js - 如何禁用 Vuetify v-expansion-panel 组件的动画?
- python - 创建 pytest 插件
- java - 带有故障安全插件的空手道,未找到功能
- arrays - 当我删除数据表中的行时,函数中的行号会发生变化
- python - 如何在`pandas``Series`中进行“加权上采样”?
- firebase - Firebase 功能在进入睡眠状态之前保持活动状态多长时间?
- python-3.x - TCP客户端/服务器:客户端程序停止时服务器中断
- javascript - td 中的输入日期在单击时不显示日历。仅在 F4 按钮上
- html - Select2 和 Bootstrap:占位符之外的选定选项