Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why write `sizeof(char)` if char is 1 by standard?

Tags:

c

coding-style

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?

like image 506
Eimantas Avatar asked Aug 30 '11 13:08

Eimantas


People also ask

Is sizeof char guaranteed to be 1?

Even if you think of a “character” as a multi-byte thingy, char is not. sizeof(char) is always exactly 1. No exceptions, ever.

Should you use sizeof char?

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.

Why size of char pointer is 8 bytes?

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*).

What is the value of sizeof 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.


1 Answers

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).

like image 130
AProgrammer Avatar answered Oct 11 '22 19:10

AProgrammer