Headlines
Loading...
Array Representation

Array Representation

int a[5]; //Garbage value

int a[5]={1,2,3,4,5}; //initialize and declare

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

//iterating the array
int a[5] = {1,2,3,4,5};
for(i=0;i<5;i++)
{
printf(“%d”, a[i]);
}

The array is a container that can hold a fixed number of items and these items should be of the same type. Most of the data structures make use of arrays to implement their algorithms. Following are the important terms to understand the concept of Array.

  • Element − Each item stored in an array is called an element.
  • Index − Each location of an element in an array has a numerical index, which is used to identify the element.


Static vs Dynamic Array
int a[5]; //size- compile time in c, run time in c++ (inside stack)

int *p;
p = (int*)malloc(5*sizeof(int)); //heap memory

// If memory is not required delete it. Otherwise, it causes a memory leak.
free(p); //deallocation of memory

//Accessing the array inside the heap
p[5]=5;

//stack array can't be resized.

// Increasing the size of the array. Same array ka size nahi badhega.
int *p = (int*)malloc(5*sizeof(int)); //p pointer of size 5
int *q = (int*)malloc(10*sizeof(int)); //q pointer of size 10
for(int i=0; i<5; i++)
{
q[i]=p[i]; //copy all elements from p to q
}

free(p); //delete p array
p=q; //p pointer points q array
q=NULL; //q pointer null

2D Array
int a[3][4];

// initialize array inside stack
int a[3][4] = {{1,2,3,4},{5,6,7,8},{9,0,1,2}};

int *a[3]; //inside stack
a[0] = (int*)malloc(4*sizeof(int)); //inside heap memory
a[1] = (int*)malloc(4*sizeof(int)); //inside heap memory
a[2] = (int*)malloc(4*sizeof(int)); //inside heap memory

int **a; //inside stack
a = (int*)malloc(3*sizeof(int)); //inside heap memory
a[0] = (int*)malloc(4*sizeof(int)); //inside heap memory
a[1] = (int*)malloc(4*sizeof(int)); //inside heap memory
a[2] = (int*)malloc(4*sizeof(int)); //inside heap memory

//access 2D arrays
for(i=0;i<3;i++)
{
for(j=0;j<4;j++)
{
printf("%d", a[i][j])
}
}


Any doubts in array representation? Please ask your doubts in the comment section. 

What's next?

0 Comments: