+ 3
Why is it that the size (memory used) of char is 4x smaller than the size of int?
Found in the new C course: In C the sizes of the data types are: int: 4 float: 4 double: 8 char: 1 This means that the number 1 takes up 4 times more memory space than the character a. Can anyone explain why?
5 Respuestas
+ 1
The size (in bytes) allocated for a certain type is closely related with how wide the range of value the said type is capable of holding, this is commonly termed as data ranges.
The char type, is one byte (8 bits), therefore its widest range is 2^8 (256), if it is char (signed char) it can contain value from -128 up to 127, but if it's unsigned char, it can contain value from 0 up to 255, both range distances sum up to 256.
As to why the size of char < size of short, and size of short < size of int and so on, it is most likely meant for us to be wiser in choosing which type to use when, in short, it teaches us efficiency in memory usage *probably*.
Besides, char was built to work with characters, ASCII to be exact, which only needed 8 bits because there is only char 0 up to char 255 in ASCII character set.
More about data ranges here:
https://msdn.microsoft.com/en-us/library/s3f49ktz.aspx
Hth, cmiiw
+ 6
Eg. char data type can take values from -128 to 127 (0 to 255 for unsigned char) 2 to power 8 is 256. Why 8? I takes 1 byte = 8 bits. It works the same for other data types.
+ 3
Because there's much more numbers than characters 🤓
If you forget about Unicode etc., one byte of memory is enough to store all standard letters A-Z/a-z, all numbers 0-9, the most common special characters !"§$%&/()[]{}=?,.- etc. and text formatting signs.
Btw, it's true that the integer 1 needs more memory than the single character 'a', but it's also true that the number 4,294,967,295, stored as an (unsigned) integer, needs less memory than the string "Hello"...
+ 2
thanks, it all makes sense now.
0
I know this post is ancient, but thanks guys. They taught me this in school, but I don't think I ever really considered it.