Wednesday, May 24, 2023
HomeSoftware EngineeringMethods to get the Size of an Array in C

Methods to get the Size of an Array in C


There isn’t actually an ordinary strategy to get the size of array in C. This implies you could do some extra work to attain getting the size of an array when utilizing C.

Creating and Looping via an Array in C

Often you’ll create an array as follows:

int objects[5] = {1, 2, 3, 4, 5};

You could possibly all the time outline the dimensions proper off the bat:

const int SIZE = 5;
int objects[SIZE] = {1, 2, 3, 4, 5};

This manner if you could loop via the array in a while, you need to use your SIZE variable.

for (int i=0; i<SIZE; i++) {
  printf("%un", objects[i]);
}

Utilizing the sizeof Operator for Array Size in C

C does nonetheless give you a sizeof operator which lets you get the dimensions of a component.

To get this to work correctly, you will want to first get the dimensions of the array after which divide it by the dimensions of one of many particular person parts. This solely works if each factor is of the very same sort.

This may enable you to get the size of array.

int objects[5] = {1,2,3,4,5};
int measurement = sizeof objects / sizeof objects[0];

// 5
printf("%u", measurement);

One other strategy to do it’s to do that:

int objects[5] = {1,2,3,4,5};
int measurement = sizeof objects / sizeof *objects;

// 5
printf("%u", measurement);
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments