Setting a buffer of char* with intermediate casting to int*

前端 未结 6 493
一向
一向 2021-01-11 17:23

I could not fully understand the consequences of what I read here: Casting an int pointer to a char ptr and vice versa

In short, would this work?

set         


        
6条回答
  •  暖寄归人
    2021-01-11 18:07

    This code might be of help to you. It shows a 32-bit number being built by assigning its contents a byte at a time, forcing misalignment. It compiles and works on my machine.

    #include
    #include
    #include
    #include
    
    int main () {
        uint32_t *data = (uint32_t*)malloc(sizeof(uint32_t)*2);
        char *buf = (char*)data;
        uintptr_t addr = (uintptr_t)buf;
        int i,j;
        i = !(addr%4) ? 1 : 0;
        uint32_t x = (1<<6)-1;
        for( j=0;j<4;j++ ) buf[i+j] = ((char*)&x)[j];
    
        printf("%" PRIu32 "\n",*((uint32_t*) (addr+i)) );
    }
    

    As mentioned by @Learner, endianness must be obeyed. The code above is not portable and would break on a big endian machine.

    Note that my compiler throws the error "cast from ‘char*’ to ‘unsigned int’ loses precision [-fpermissive]" when trying to cast a char* to an unsigned int, as done in the original post. This post explains that uintptr_t should be used instead.

提交回复
热议问题