sizeof
is a built-in compile-time operator, so values are computed at compile-time, not during run-time. (except if used to compute the value of a VLA.) Note, parenthesis are optional, with this operator, (with a few exceptions) although often used by some as a readability preference.
int intvar[] = {1,2,3,4,5,6,7,8,9,0);
size_t size = sizeof(intvar);
char strvar[] = {"this is 10"};
size = sizeof(strvar);
float fltvar[] = {1.2, 2.1, 3.4, 5.6, 7.5, 8.9, 3.7, 5.2, 5.89, 54.0};
size = sizeof(fltvar);
If you would like to know how many elements in say an an array of strings, eg such as
char str_array[][80] = {"this", "is", "a" "string", "array"};
divide the size of the array by the size of one of its elements as shown here:
size_t string_count = sizeof(str_array)/sizeof(str_array[0]);
in this case resulting in 5
strings. Note that for an array of strings such as this, the memory for each string must be the same, in this case 81
(80
+ 1
for NULL
terminator)
Edit
Question in comments: For the declaration float data[12]; with the compiler assigning a starting address of 0005 in decimal. What would be the address of the last byte?
First, when creating float data[12];
, the OS provides the address, based on among other things what is the first location with a block contiguous memory big enough to contain 12*32 bytes of memory. So it is arbitrary the we can set the location to 5 (which is equivalent to 0x0005
)
float data[12];
printf("Address of last element in data when memory starts at 0x0005 is %p\n, &data[11] - &data[0] + 0x0005);
float data[12];
float *loc_0 = &data[0];
float *loc_12 = &data[11];
// memory location can now be determined by the simple expression:
// loc_12 - loc_0 + 0x0005
printf("Address of last element in data when memory starts at 0x0005 is 0x%.4p\n", (void *)(loc_12 - loc_0 + 0x0005));
(For the record though, starting at address == 0005 is unnatural as memory addresses are given by the OS without consulting the programmer first, so there is little that can be done to actually start at address == 0005.)