当我运行以下代码时,它会出现段错误:
#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);
}
}
我实际上是在尝试做一个类型转换的例子。如何解决段错误?
最佳答案
我猜测是您使用的是 64 位机器,其中指针是 64 位。当你这样做时,这会导致大问题(和 undefined behavior )
hacky_nonpointer = (unsigned int) char_array;
因为 int
类型通常仍然只有 32 位。
一旦你尝试过这个,然后把它全部扔掉,然后忘记一切!这是糟糕的代码,做了真正的程序不应该做的坏事。
关于c - 类型转换的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51429480/