c - 类型转换的段错误

标签 c memory

当我运行以下代码时,它会出现段错误:

#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/

相关文章:

c - 重新分配失败

c - C中的结构

C - 初始化结构中的指针

Python不在for循环中释放内存

c++ - 从缓冲区指针计算堆栈中的返回地址

c - 为什么不匹配的原型(prototype)和定义与空参数列表在 GCC 和 Clang 中给出不同的结果?

c - if 语句中的字符串比较不起作用

c++ - CUDA:将统一内存与类和数组一起使用

c++ - OpenCV Mat 中的动态内存释放错误

linux - 如何在 Intel CPU 上找到 L3 Cache 参数?