Is it necessary to multiply by sizeof( char ) when manipulating memory?

后端 未结 8 1099
走了就别回头了
走了就别回头了 2021-01-01 22:26

When using malloc and doing similar memory manipulation can I rely on sizeof( char ) being always 1?

For example I need to allocate memory for N elements of type

8条回答
  •  一生所求
    2021-01-01 22:54

    By definition, sizeof(char) is always equal to 1. One byte is the size of character in C, whatever the numbers of bits in a byte there is (8 on common desktop CPU).

    The typical example where one byte is not 8 bits is the PDP-10 and other old, mini-computer-like architectures with 9/36 bits bytes. But bytes which are not 2^N are becoming extremely uncommon I believe

    Also, I think this is better style:

    char* buf1;
    double* buf2;
    
    buf1 = malloc(sizeof(*buf1) * N);
    buf2 = malloc(sizeof(*buf2) * N);
    

    because it works whatever the pointer type is.

提交回复
热议问题