C - Array Array Size

Introduction

The sizeof operator works with arrays too. Suppose that you declare an array with the following statement:

double values[5] = { 1.5, 2.5, 3.5, 4.5, 5.5 };

You can output the number of bytes that the array occupies with the following statement:

printf("The size of the array, values, is %zu bytes.\n", sizeof values);

You can get the number of bytes occupied by a single element with the expression sizeof values[0].

The memory occupied by an array is the size of a single element multiplied by the number of elements.

You can use the sizeof operator to calculate the number of elements in an array:

size_t element_count = sizeof values/sizeof values[0];

You can have written the previous statement to calculate the number of array elements as follows:

size_t element_count = sizeof values/sizeof(double);

Demo

#include<stdio.h>

int main(void)
{
  double values[5] = { 1.5, 2.5, 3.5, 4.5, 5.5 };
  size_t element_count = sizeof(values) / sizeof(values[0]);
  printf("The size of the array is %zu bytes ", sizeof(values));
  printf("and there are %u elements of %zu bytes each\n", element_count, sizeof(values[0]));

  return 0;//from  ww  w  . j  a  v  a2  s .c  o  m
}

Result

Related Topics