Size matters!
The sizeof
operator in C is used to determine the size, in bytes, of a data type or a variable. Here's a sample code that demonstrates how sizeof
works in various contexts:
#include <stdio.h>
int main() {
// Size of basic data types
printf("Size of int: %lu bytes\n", sizeof(int));
printf("Size of float: %lu bytes\n", sizeof(float));
printf("Size of double: %lu bytes\n", sizeof(double));
printf("Size of char: %lu bytes\n", sizeof(char));
// Size of data types in an array
int intArray[5];
printf("Size of intArray: %lu bytes\n", sizeof(intArray));
// Finding the length of an array
int arrayLength = sizeof(intArray) / sizeof(int);
printf("Length of intArray: %d elements\n", arrayLength);
// Size of a structure
struct SampleStruct {
int x;
char y;
double z;
};
struct SampleStruct myStruct;
printf("Size of SampleStruct: %lu bytes\n", sizeof(struct SampleStruct));
printf("Size of myStruct: %lu bytes\n", sizeof(myStruct));
// Size of a pointer
int *intPtr;
printf("Size of intPtr: %lu bytes\n", sizeof(intPtr));
// Size of a pointer to a structure
struct SampleStruct *structPtr;
printf("Size of structPtr: %lu bytes\n", sizeof(structPtr));
// Size of an expression
int a = 5;
printf("Size of 5 + 3: %lu bytes\n", sizeof(5 + 3));
printf("Size of a + 3: %lu bytes\n", sizeof(a + 3));
return 0;
}
This code demonstrates the use of sizeof
with various data types, arrays, structures, pointers, and expressions. Note that the size of a structure is the sum of the sizes of its members, and padding may be added for alignment purposes. The size of an array is the size of one element multiplied by the number of elements. The size of a pointer is typically the same regardless of the type it points to. The size of an expression depends on the type of the result of the expression.