What are the rules for casting pointers in C?

前端 未结 5 632
梦毁少年i
梦毁少年i 2020-12-04 04:35

K&R doesn\'t go over it, but they use it. I tried seeing how it\'d work by writing an example program, but it didn\'t go so well:

#include 

        
5条回答
  •  盖世英雄少女心
    2020-12-04 05:22

    char c = '5'
    

    A char (1 byte) is allocated on stack at address 0x12345678.

    char *d = &c;
    

    You obtain the address of c and store it in d, so d = 0x12345678.

    int *e = (int*)d;
    

    You force the compiler to assume that 0x12345678 points to an int, but an int is not just one byte (sizeof(char) != sizeof(int)). It may be 4 or 8 bytes according to the architecture or even other values.

    So when you print the value of the pointer, the integer is considered by taking the first byte (that was c) and other consecutive bytes which are on stack and that are just garbage for your intent.

提交回复
热议问题