在C中创建指针

标签 c

我使用 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/

相关文章:

java - 如何缩短 Android 中的编码?

c - 骰子游戏坚持原始分数但成功循环

C 变量默认初始化

c - setlocale 卡在 Windows 上

c - 了解 cairo_scale()

c - 如何通过引用传递动态分配的二维数组中的子数组?

c - 这段代码是怎么工作的?它应该由于缓冲区溢出而崩溃,但我得到的输出为 "stackoverflow"

python - 如何在没有循环的情况下在 Cython 中创建空的 char 数组

c - 解释类型转换如何在 C 中从 int 到 short 的位级别工作

我们可以在 make 中运行一个 python 脚本来生成一些 .c 和 .h 文件,然后构建一个镜像吗?