我使用 Ubuntu 14.10 和 GCC。我正在尝试创建一个具有无符号整数类型的指针,但我收到以下消息:
Segmentation fault (core dumped)
这是我的代码。我使用 gdb 并认为该错误与我的 printf
语句有关:
#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++) {
printf("[hacky_nonpointer] points to 0x%08x which contains the char '%c' \n",
hacky_nonpointer, *(char *(hacky_nonpointer)));
hacky_nonpointer = hacky_nonpointer + sizeof(char);
}
hacky_nonpointer = (unsigned) int_array;
for (i = 0; i < 5; i++) {
printf("[char pointer] points to %08x, which contains the integer %d\n",
hacky_nonpointer, *((int *)hacky_nonpointer));
hacky_nonpointer = hacky_nonpointer + sizeof(int);
}
return 0;
}
最佳答案
unsigned int
可能不够大,无法容纳指针。如果可用,您应该使用 stdint.h
中的 uintptr_t
(如果没有,则使用 size_t
)。
关于在C中创建指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28722521/