Home > Tutorials > C Tutorials > Programming In C: Counting Array Elements & Sizes

Programming In C: Counting Array Elements & Sizes

Size of an Array

How much space in memory does an array occupy? We can calculate this by using a special operator: sizeof. This operator calculates how many bytes of memory are occupied by an array. For example, here is an array:

numbers[3] = { 8, 29, 63 };

Using sizeof, I can write:

printf(“The numbers array occupies %d bytes of memory.”, sizeof numbers);

Let’s try it in a program:

#include<stdio.h>
void main( )
{
int numbers[3] = { 8, 29, 63 };
printf(“The numbers array occupies %d bytes of memory.”, sizeof numbers);

 

Save your source code as numsize.c. Compile it. Link it. Run it.

Size of an Element

How much memory space does an array element occupy? Let’s use this array:

float prices[4] = { 19.95, 32.50, 16.75, 99.99 };

We can discover how much space each element occupies by using sizeof(prices[0])

Let’s try it in a program:

#include<stdio.h>
void main( )
{
float prices[4] = { 19.95, 32.50, 16.75, 99.99 };
printf(“Each price occupies %d bytes of memory.”, sizeof(prices[0]));

 

Save your source code as elsize.c. Compile it. Link it. Run it.

Counting Array Elements

If you don’t know how many elements are in an array, you can use a variable and the sizeof operator together.

Let’s use this array:

int years[3] = { 1870, 1961, 2000 };

To count the number of elementsdivide the total size by the size of one element, like this:

int numelementssizeof(years)/sizeof(years[0]);

Let’s try it in a program:

#include<stdio.h>
void main( )
{
int years[3] = { 1870, 1961, 2000 };
int numelements = sizeof(years)/sizeof(years[0]);
printf(“The years array has %d elements.”, numelements);

 

Save your source code as numel.c. Compile it. Link it. Run it.

 

About Michael Boguslavskiy

Michael Boguslavskiy is a full-stack developer & online presence consultant based out of New York City. He's been offering freelance marketing & development services for over a decade. He currently manages Rapid Purple - and online webmaster resources center; and Media Explode - a full service marketing agency.

Check Also

How To Populate A DIV via an HTML SelectBox, PDO, and jQuery

Imagine you have a database full of information, and you want to let users browse ...