C Program To Find The Memory Size Of Arrays

In C programming, one of the frequent problem is to find the total memory size of an array. If the array is string, integer, or a floating type, the size varies. This post will teach you to write a C program that will compute the memory size of the array automatically.

Problem Definition

Once you have defined an array, its is very difficult to know the size of the array that totally depends on the data type of the array. The main primitive types are listed below.

String Size – 1 bytes

Integer – 2 bytes

Float – 4 bytes

There are other types that depends on these primitive types. One such user-defined size is an array.

This program will take an array and determine the size of each element of the array and add the total size into a single variable. Once finished the program will display the total size of the array.

Program Code

#include <stdio.h>
int main()
{
    int arr[15]= {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
    int x = 0;
    int i;

for (i =0;i< 15;i++)
{
    x = x + sizeof(arr[i]);
}
printf("%d",x);
return 0;
}

The program code above works for a single integer array type, if you want to change it to a string array or a float, it will still give you the correct output with the total array memory size.

Output

30

In the program above, the size of each integer is 2 bytes and there are 15 elements for the array. Therefore, the total size is 15 * 2 =30 bytes.

You may try this program with other data types and check results.

Please support us by disabling your adblocker or whitelist this site from your adblocker. Thanks!

turn of adblocker imag