c - 分段错误,转换到/从指针到/从不同大小的整数
问题描述
下面的代码是我正在阅读的一本书的示例,我尝试确保它与书中的代码完全准确,但它仍然不起作用。运行它时,我得到“分段错误(核心转储)”。显然这是一个例子,“使用类型转换定义的数据类型,任何大到足以容纳四字节值的东西都可以像 void 指针一样工作”。我想知道为什么它不工作,也许学习如何以一种正常运行的方式来做。如果这是造成愚蠢错误的原因,请提前道歉。
#include <stdio.h>
int main() {
int i;
char char_array[5] = {'a', 'b', 'c', 'd', 'e'};
int int_array[5] = {1,2,3,4,5};
unsigned int hacky_nonpointer;
hacky_nonpointer = (unsigned int) char_array;
for(i=0;i<5;i++) { // Iterate through the int array with the int_pointer.
printf("[hacky_nonpointer] points to %p, which contains the char '%c'\n", hacky_nonpointer, *((char *) hacky_nonpointer));
hacky_nonpointer = hacky_nonpointer + sizeof(char);
}
hacky_nonpointer = (unsigned int) int_array;
for(i=0;i<5;i++) { // Iterate through the int array with the int_pointer.
printf("[hacky_nonpointer] points to %p, which contains the integer %d\n", hacky_nonpointer, *((int *) hacky_nonpointer));
hacky_nonpointer = hacky_nonpointer + sizeof(int);
}
}
解决方案
推荐阅读
- java - Crudrepository 如何找到最后日期之间的?
- javascript - 为什么 express 的 res.download() 方法会导致“请求中止”错误?
- excel - 遍历表格并剪切并粘贴到另一张纸上
- ruby - 将字节数组转换为十六进制字符串
- c# - 测试 .NET Core 控制器视图组件
- widget - JUPYTER 实验室小工具
- angularjs - 如何实现显示更多
- 使用 angularjs ng-repeat 指令?
- google-apps-script - Google App Script 是否有键值对?
- nunit - Nunit:ParallelScope Self+Children、Fixture+Children 和 All 之间的区别
- docker - 上下文截止日期延长 - prometheus - 在 docker 上运行时