I was doing some C coding and after reading some C code I've noticed that there are code snippets like
char *foo = (char *)malloc(sizeof(char) * someDynamicAmount);
So I want to ask what's more C-ish way to allocate memory for char array? Use sizeof(char)
and supposedly future-proof the code against any standard changes or omit it and use the number directly?
Even if you think of a “character” as a multi-byte thingy, char is not. sizeof(char) is always exactly 1. No exceptions, ever.
sizeof( char ) is always equal to 1 and does not depend on used environment. While sizeof( char * ) is implementation-defined and can be equal for example to 2, 4 or 8 bytes or even something else.
8 is the size of a pointer, an address. On 64 bit machine it has 8 bytes. Show activity on this post. If you are on a 64 bit computer, the memory addresses are 64 bit, therefore a 64 bit (8 bytes x 8 bits per byte) numeric value must be used to represent the numeric pointer variable (char*).
The sizeof operator returns 1 , meaning 1 byte, when used with the char , unsigned char , or signed char types. The number of bits in a char , is defined in the limits. h header, using the macro CHAR_BIT . The following example illustrates, how to get the number of bits for other types.
The more Cish way would be
char* foo = malloc(someDynamicAmount * sizeof *foo);
referencing the variable and not the type so that the type isn't needed. And without casting the result of malloc (which is C++ish).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With