Basics of Array Data Structures in C/C++.

Arrays are collection of elements stored in continuous memory locations.

Ways to declare array in c

‘data-type-‘ ‘name'[‘size’]

int a[10];

This will create an array of allocated size 10 in the stack. It is necessary to declare the size of the array during initialisation.

This will give a compilation error

int a[]; #compilation error

Other ways to declare and initialise arrays

int a[10]={2,3,4,5,6} #declared like {2,3,4,5,6,0,0,0,0}
int a[5]={0} #{0,0,0,0,0}

Elements can be accessed using their index. Index start from 0 and last index is length of array – 1.

int a[5]={0,1,2,3,4}
printf("%d",a[2]); #2
printf("%d",a[4]); #4
printf("%d",a[5]); #Array out of range

Each element is stored at some memory location. Say, first value at index 0 is at memory location 200, then the memory of next element at index 1 is at 202(if the size of int is 2 in the given compiler), similarly 204, 206.. of the following elements

Problem in above declaration of Array – What if we want to declare the size of the array later, or input the size of array from user. Then we use dynamic initialisation of array.

In dynamic initialisation we declare a pointer that contains the memory address of that array.

#include<stdio.h>
#include<stdlib.h>
int main(){
    int *p,n,i; 
    scanf("%d",&n);
    p=(int *)malloc(n*sizeof(int));
    for(i=0;i<n;i++){
        scanf("%d",&p[i]);
    }
    for(i=0;i<n;i++){
        printf("%d",p[i]);
    }
}

The above code is for dynamic initialisation in which first the size of array is input from the user then array is created using the malloc function.

LEAVE A REPLY