Arrays in C

May 15, 2021 0 Comments

Arrays in C

Arrays in C, It’s a kind of data structure that can store a fixed-size sequential collection of elements of the same type.

It is used to store a collection of data, and a collection of variables of the same type.

Formally syntax is

data_type name[size];
#include<stdio.h>
int main()
{
	int a[5] = {10,20,30,40,50};
	int i = 0;
	for(;i < 5; i++) {
		printf("%d ",a[i]);
	}

	return 0;
}

Multidimensional Array Syntax:

Arrays in C, Multidimensional Array syntax

data_type name[row][col];
#include<stdio.h>
int main()
{
        int a[2][3] = {{10,20,30},{40,50,60}};
        int i = 0, j=0;
        for(i=0;i < 2; i++) {
                for (j=0; j<3; j++) {
                        printf("%d ",a[i][j]);
                }
        }
        printf("\n");

        return 0;
}

variable length arrays:

variable-length arrays introduced as part of c99 standards and can’t be initialized at the time of deceleration.

#include<stdio.h>
int main() {
     int size =5;
     int arr[size],i=0;
     for(i=0; i< size; i++) {
         arr[i] = i+2;
     }
     for(i=0; i< size; i++) {
         printf("%d ",arr[i]);
     }
     return 0;
}

Pointer to Array:

Syntax:

data_type (*name)[size];

Example:

int (*P)[5]; // p is a pointer to an array of 5 integers.

int *q[5]; // q is an array of 5 pointers to an integer.

Dereference pointer to an array:

Dereference pointer to an array will always return a pointer to the first element in the array.

Example:

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

int (*q)[5];

q = &a;

int *p;

p = *q; // *q returns pointer to an integer
int b = **q; // **q returns first integer in array of 5 integers

int a[5];

int d[3][4];

a –> pointer to integer

d –> pointer to array of 4 columns of type integers

&a –> pointer to array of 5 integers

&d –> pointer to an array of 3 rows and 4 columns of type integers

*a –> returns integer

*d –> pointer to integer

**d –> integer.

Share This: