Memory Size Calculator
C
Medium
3 views
Problem Description
By printing the size of different datatypes (char, int, float, double, long, pointers). Then create array of each type and verify that array size = element_count * sizeof(type).
Official Solution
#include <stdio.h>
int main() {
int n = 5;
/* ---- Size of basic data types ---- */
printf("Size of char = %zu bytesn", sizeof(char));
printf("Size of int = %zu bytesn", sizeof(int));
printf("Size of float = %zu bytesn", sizeof(float));
printf("Size of double = %zu bytesn", sizeof(double));
printf("Size of long = %zu bytesn", sizeof(long));
printf("Size of pointer= %zu bytesnn", sizeof(int*));
/* ---- Arrays of each type ---- */
char cArr[5];
int iArr[5];
float fArr[5];
double dArr[5];
long lArr[5];
int *pArr[5]; // array of pointers
/* ---- Verify array size formula ---- */
printf("char array size = %zu (Expected: %zu)n",
sizeof(cArr), n * sizeof(char));
printf("int array size = %zu (Expected: %zu)n",
sizeof(iArr), n * sizeof(int));
printf("float array size = %zu (Expected: %zu)n",
sizeof(fArr), n * sizeof(float));
printf("double array size = %zu (Expected: %zu)n",
sizeof(dArr), n * sizeof(double));
printf("long array size = %zu (Expected: %zu)n",
sizeof(lArr), n * sizeof(long));
printf("pointer array size= %zu (Expected: %zu)n",
sizeof(pArr), n * sizeof(int*));
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!