Given this code snippet:
#include <stdio.h>
int main() {
short i = 20;
char c = 97;
printf("%d, %d, %d\n", sizeof(i), sizeof(c), sizeof(c + i));
return 0;
}
Why is sizeof(c + i) == 4
?
Operands of type char are promoted to type int and the actual addition is performed within the domain of int (or unsigned int , depending on the properties of char on that platform). So your a + b is actually interpreted as (int) a + (int) b . The result has type int and sizeof(int) is apparently 4 on your platform.
The sizeof keyword refers to an operator that works at compile time to report on the size of the storage occupied by a type of the argument passed to it (equivalently, by a variable of that type). That size is returned as a multiple of the size of a char, which on many personal computers is 1 byte (or 8 bits).
If an unsized array is the last element of a structure, the sizeof operator returns the size of the structure without the array. buffer = calloc(100, sizeof (int) ); This example uses the sizeof operator to pass the size of an int , which varies among machines, as an argument to a run-time function named calloc .
The sizeof operator applied to a type name yields the amount of memory that can be used by an object of that type, including any internal or trailing padding. The result is the total number of bytes in the array. For example, in an array with 10 elements, the size is equal to 10 times the size of a single element.
c + i
is an integer expression (integer promotion!), so sizeof()
returns sizeof(int)
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