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:
Using sizeof, I can write:
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:
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:
To count the number of elements, divide the total size by the size of one element, like this:
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.
Leave a comment