首页 > 解决方案 > 分段错误,转换到/从指针到/从不同大小的整数

问题描述

下面的代码是我正在阅读的一本书的示例,我尝试确保它与书中的代码完全准确,但它仍然不起作用。运行它时,我得到“分段错误(核心转储)”。显然这是一个例子,“使用类型转换定义的数据类型,任何大到足以容纳四字节值的东西都可以像 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);
        }
}

标签: cpointers

解决方案


推荐阅读