简体   繁体   中英

Cast pointer type in C

#include <stdio.h>

  int main () {
      char c = 'A';
      int *int_ptr;
      double *double_ptr;

      *int_ptr = *(int *)&c;
      *double_ptr = *(double *)&c;

      printf("Original char = %c \n", c);
      printf("Integer pointer = %d \n", *int_ptr);
      printf("Double pointer = %f\n", *double_ptr);

      return 0;
  }

The questing is – Why can't I assign the double_ptr using this code, because it causes segmentation fault, but works fine for integer?

As I understand char is 1-byte long and int is 4-bytes long, so double is 8 bytes-long.

By using expression *(double *)&c I expect the following:

  1. & – Get the memory address of c.
  2. (double *) – pretend that this is a pointer to double.
  3. *() – get the actual value and assign it to double var.

Your code has Undefined Behaviour. Therefore anything could happen.

The UB is because you are casting a char which is one byte to types that are 4 and 8 bytes, which means you are (potentially) accessing memory out of bounds, or with the wrong alignment.

Whether any of this will "work" or "not work" on any particular system is not very relevant, because the code is erroneous.

在您的程序中,将char类型转换为int*double* ,然后进行取消引用将从内存中获取一些额外的字节,这是未定义的行为

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM