Curriculum
Course: C basic
Login

Curriculum

C basic

C Introduction

0/1

C Get Started

0/1

C Comments

0/1

C Constants

0/1

C Operators

0/1

C Break and Continue

0/1

C User Input

0/1

C Memory Address

0/1

C Structures

0/1
Text lesson

Array Size

Get Array Size or Length

To get the size of an array, you can use the sizeof operator:

Example

int myNumbers[] = {10, 25, 50, 75, 100};
printf(“%lu”, sizeof(myNumbers)); // Prints 20

 

Why did the outcome display 20 instead of 5, despite the array comprising 5 elements?

This occurs because the sizeof operator provides the size of a type in bytes.

As covered in the Data Types chapter, an int type typically occupies 4 bytes. Thus, in the example above, 4 x 5 (4 bytes x 5 elements) equals 20 bytes.

Understanding the memory size of an array is beneficial for larger programs that demand effective memory management.

However, if you simply aim to determine the number of elements within an array, you can employ the following formula, which divides the size of the array by the size of one array element:

Example

int myNumbers[] = {10, 25, 50, 75, 100};
int length = sizeof(myNumbers) / sizeof(myNumbers[0]);

printf(“%d”, length);  // Prints 5

Making Better Loops

In the array loops section in the previous chapter, we specified the size of the array in the loop condition (i < 4). However, this approach is not ideal as it will only function correctly for arrays of a specific size.

By employing the sizeof formula from the example above, we can now create loops that accommodate arrays of any size, ensuring greater versatility and sustainability.

Instead of specifying:

Example

int myNumbers[] = {25, 50, 75, 100};
int i;

for (i = 0; i < 4; i++) {
  printf(“%d\n”, myNumbers[i]);
}

It’s preferable to express:

Example

int myNumbers[] = {25, 50, 75, 100};
int length = sizeof(myNumbers) / sizeof(myNumbers[0]);
int i;

for (i = 0; i < length; i++) {
  printf(“%d\n”, myNumbers[i]);
}