Arrays in C – Part 2

Read: Arrays in C – Part 1

In the last tutorial I gave you an overview of arrays in C and I also told you about the declaration and initialization of arrays. Till now we have also completed the topic to print the values of array on the screen. Today I will tell you about how to take values inside an array by user. So lets start it with some program.

#include<stdio.h>

void main()
{
 int x[5];
 int i;
 printf(" Enter the values in an arrayn ");

 for(i=0;i<5;i++)
 {
  scanf("%d",&x[i]); //taking values inside an array
 }

 for(i=0;i<5;i++)
 {
  printf("n %d ",x[i]); //printing values on the screen
 }
}

Output

Arrays in C - Part 2

Explanation

  • In our program I have declared “x” as an integer array with 5 elements.
  • By using a for loop I have taken 5 values from the user.
  • Consider carefully the subscript I have used inside scanf() function which is x[i].
  • Almost similar loop is used to print the values inside that array.

To easily understand the working of arrays you should know about the fact.

How array elements are stored in memory?

Consider the below declaration of an array.

int x[8];

When compiler detects some array declaration then it immediately reserves the space for it. In our case I have declared the integer array with 8 elements. When compiler detects it, it will immediately reserve 16 bytes in memory (2 byte for each element). In our case we do not initialize the array with its declaration so it will contain some garbage value by default. The reason behind the garbage values are due to its storage class. By default array has “auto” storage class.

Array consists of contiguous memory locations. It means all the values inside an array will be stored in contiguous memory parts. Checkout the below figure.

Arrays in C - Part 2

Bounds Checking

Consider the below code

int x[8];
x[10]=98;

The size of our array is only 8 elements. But we are storing the value 98 at 10th location. How is it possible? Its certainly not possible. But remember for this situation the compiler will not obstruct you by giving some error. It will not give any warning to you. Because there is no bounds checking is done in arrays. Compiler never checks the limit of the array while storing the values.

So where will this value be stored?
It can be stored anywhere. Probably just after contiguous location of the array. Or top of the array. It can stored anywhere. And remember sometimes small mistakes like that can completely ruin your program and can even hang computer. So I would strongly suggest you to remember this mistake while storing values inside an array.

Leave a Comment

Your email address will not be published. Required fields are marked *