Array in C – What is array in C Programming Language

Array in C – What is array in C Programming Language

Array in C Programming is a particular sort of data structure called an array can hold a fixed-size sequential collection of identical-type elements. It is important to think of an array as a collection of variables of the same type even though it is used to store a collection of data.

You define one array variable, such as numbers, and use numbers[0], numbers[1], and…, numbers[99] to represent individual variables rather than specifying individual variables, such as number 0, number1,…, and number99. An index is used to reach a specific element in an array.

You must test the C Language code provided in this lesson in your code editor to validate it. However, if you prefer to execute this code online, we also provide a free C Online Compiler for testing your C Language code.

Basics of Programming with Strings ...
Basics of Programming with Strings in Python (Video 07)

Contiguous memory addresses make up all arrays. The first element has the lowest address, and the last piece has the highest address.

What is array in C Programming Language?

The definition of an array in C is a way to group together several items of the same type. These things or things can have data types like int, float, char, double, or user-defined data types like structures.

All of the components must, however, be of the same data type in order for them to be stored together in a single array. The items are kept in order from left to right, with the 0th index on the left and the (n-1)th index on the right.

Single-dimensional arrays and multidimensional arrays are the two types of arrays available in C.

  • Single Dimensional Arrays: The simplest type of array found in C is the single dimensional array, sometimes known as a 1-D array. This kind of array has members with comparable kinds, and its indices can be used to access those elements.
Array in C
  • Multi-dimensional Arrays: A 2-D array is the most prevalent sort of multi-dimensional array used in the C programming language. However, depending on the user’s system’s compiler, there may be more than two dimensions. These arrays are made up of elements that are arrays.

Why Do We Need Arrays?

If there are only a few components, such as three variables, we can define them individually as var1, var2, and var3. However, if we need to store a lot of variables, we can utilize arrays.

Let’s use a real-world illustration. Consider creating a program that prints 1-100 digits. Now, there are two ways to accomplish this in the C language.

The first step is to create 100 variables, save the digits 1 through 100 separately in each variable, and then print each digit. The second approach involves making a 100-by-100 array and using a loop to store the numbers in it. In linear complexity, these digits can be produced using a single loop.

Since it is easier to store these values in a single array rather than having to create 100 variables, it is obvious that the second solution is more optimized and preferable than the first one.

Array in Details in C

Array in Details in C is important because they are crucial to C, arrays demand a lot more attention. A C programmer should understand the following crucial array principles.

ConceptDescription
Multi-dimensional arraysMultidimensional arrays are supported in C. The two-dimensional array is the most basic type of multidimensional array.
Passing arrays to functionsBy giving the function the array’s name without an index, you can send it a pointer to the array.
Return array from a functionA function may return an array in C.
Pointer to an arrayWith just the array name and no index, you can create a pointer to the first element of an array.
Array in Details in C

Declaration and Initialization of Array in C

The declaration and initialization of an array in C can be done in a variety of ways. Any data type (such as an int, float, double, or char) may be declared as an array in C. An array in C can be declared and initialized in the ways shown below.

Array Declaration by Specifying the Size in C

Declaring an array in C involves stating its size or its element count. The maximum number of elements that an array can contain is specified by its size.

The newest version of C allows you to declare an array by either providing a user-specified size or by simply declaring the size at the time of the declaration. An array can be declared using the following syntax by simply stating its size.

For Example:

// declare an array by specifying size in [].
int my_array1[100];
char my_array2[45];
// declare an array by specifying user defined size.
int size = 100;
int my_array3[size];

When an array is created but no values are assigned to it, it maintains a trash value. Like any uninitialized variable, any uninitialized array value will return a trash value if you access it.

Array Declaration by Initializing Elements

When an array is declared, it can be initialized. The compiler will allocate an array with the same size as the number of array elements when using this way of array declaration. An array can be simultaneously declared and initialized using the following syntax.

// initialize an array at the time of declaration.
int my_array[] = {100, 200, 300, 400, 500}

Although the array size has not been given in the above syntax, the compiler will allocate a size of 5 integer elements to the formed array of 5.

Array Declaration by Specifying the Size and Initializing Elements in C

Another way to create an array is to declare it, set its size, and then assign its components. The prior approach of creating arrays is not the same as this one.

The rest of the items will automatically be initialized to 0 by the compiler in this case if the number of initialized elements is fewer than the size of the array supplied. For clarification, refer to the following syntax.

// declare an array by specifying size and 
// initializing at the time of declaration
int my_array1[5] = {100, 200, 300, 400, 500}; // my_array1 = {100, 200, 300, 400, 500}
//  
int my_array2[5] = {100, 200, 300};  // my_array2 = {100, 200, 300, 0, 0}

My array1 is a 5-element array with all five items populated in the array syntax above. My array2 has a 5 element array, however only three of its entries have been initialized. The compiler will initialize the final two entries of the second array to 0.

Array Initialization Using a Loop in C

Array Initialization Using a Loop in C can also be used to initialize an array. Beginning with 0, the loop accesses all array indices by iterating from 0 to (size – 1). The array elements are initialized using a “for loop” with the following syntax. The most typical method of initializing an array in C is this one.

// declare an array.
int my_array[5];
// initialize array using a "for" loop.
int i;
for(i = 0; i < 5; i++) 
{
    my_array[i] = 2 * i;
}
// my_array = {0, 2, 4, 6, 8}  

An array of size 5 is specified first in the syntax above. A for loop is then used to initialize the array, iterating through the elements of the array from index 0 to (size – 1).

Access Array Elements in C

Access Array Elements in C by indexing the array name, an element can be obtained. After the array’s name, do this by adding square brackets around the element’s index.

For example:

double salary = balance[20];

The preceding sentence will choose the array’s tenth element and assign its value to the salary variable. The example that follows demonstrates the usage of all three of the aforementioned ideas, namely declaration, assignment, and accessing arrays.

Example Access Array Elements in C

#include <stdio.h>
 
int main () {
   int n[ 10 ];
   int x,y;
 
            
   for ( x = 0; x < 10; x++ ) {
      n[ x ] = x + 200; 
   }
   
   
   for (y = 0; y < 10; y++ ) {
      printf("Element Array[%d] = %d\n", y, n[y] );
   }
 
   return 0;
}

Output of the above example

Element Array[0] = 200
Element Array[1] = 201
Element Array[2] = 202
Element Array[3] = 203
Element Array[4] = 204
Element Array[5] = 205
Element Array[6] = 206
Element Array[7] = 207
Element Array[8] = 208
Element Array[9] = 209

You can try to test here the example above!

Input and Output Array Elements in C

By receiving user input and putting it in the array, array values can be stored. The following illustration demonstrates this:

// input an integer element and store it 
// in 1st position of the array
​scanf("%d", &my_array[0]);
// input a float element and store it 
// in ith position of the array
scanf("%f", &my_array[i-1]);

The printf() method can also be used to display array elements in the output. The position of the element to be printed is indicated by the index, which is given. The following illustration demonstrates this:

// print the element stored at 1st position or 0th index
printf("%d", my_array[0]);
// print the element stored at ith position or (i - 1)th index
printf("%d", my_array[i-1]);

Advantages of Array in C

In the C programming language, arrays are extremely important. While programming, they offer the programmers a number of benefits. Among them are:

  • Because we can keep numerous elements in an array at once and avoid having to write or initialize them repeatedly, arrays help to optimize and clean up the code.
  • A single loop can be used to iterate through every element in an array.
  • Sorting is significantly simpler using arrays. You can sort elements by writing a few lines of code.
  • Any array element can be retrieved in O(1) time in any direction, from the front or the back.
  • In an array, elements can be added or removed with linear complexity.

Disadvantages of Array in C

There are drawbacks to everything that is advantageous. The same is valid for arrays. The array in C has a few drawbacks, some of which are listed below:

  • Accessing an array improperly: The fact that arrays are statically allocated is their primary drawback. This implies that their size cannot be changed once it has been initialized. Take into account the following example to better grasp this point:
#include <stdio.h>
int main()
{
    //declaring the array of size 20
    int my_array[20];
    //initialising the array elements
    for (int x = 0; x < 20; x++)
    {
        //i will be the value of e
        //very ith element of the array
        my_array[x] = x;
    }
    // Print value at index 5 of the array
    printf("Element at index 5"
           " is %d\n",
           my_array[5]); 
    // Print value at index 13 of the array
    printf("Element at index 13"
           " is %d\n",
           my_array[13]);
    // Print value at index 21 of the array
    printf("Element at index 21"
           " is %d",
           my_array[21]);
    return 0;
}

Output of the above example

Element at index 5 is 5
Element at index 13 is 13
Element at index 21 is 32764

Since the array arr’s initial value in the example above is 20, printing the values of elements up to the index 20 produces the expected results.

However, the element at index 21 is returning a garbage value when we attempt to print it. The array was accessed outside of the bound index, which is why.

You can try to test here the example above!

The functions malloc() and calloc() can be used to fix this problem. These operations perform dynamic memory allocation. We have a free() function that enables us to freely release any memory that is no longer needed.

The example below demonstrates this:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    //*ptr will be storing the base
    //address of the array elements
    int *ptr;
    int size, x;
    // size of the array will be 5
    size = 10;
    printf("Size of the array is: %d\n", size);
    // allocating the array memory
    //dynamically using malloc()
    ptr = (int *)malloc(size * sizeof(int));
    // Checking whether the memory has
    //been successfully allocated by malloc
    if (ptr == NULL)
    {
        printf("Memory has not been allocated allocated\n");
        exit(0);
    }
    else
    {
        // Memory has been successfully allocated
        printf("Memory has been allocated successfully\n");
        // initializing the array elements
        for (x = 0; x < size; ++x)
        {
            ptr[x] = x + 1;
        }
        // Print the elements of the array
        printf("The elements of the array are: ");
        for (x = 0; x < size; ++x)
        {
            printf("%d ", ptr[x]);
        }
    }
    return 0;
}

Output of the above example

Size of the array is: 10
Memory has been allocated successfully
The elements of the array are: 1 2 3 4 5 6 7 8 9 10

You can try to test here the example above!

  • Homogeneity: We can store only a single type of element in the array i.e., arrays are homogeneous. We can not use it as a template. For example, if the array data type is char, then only characters can be stored in the array. If you try to store integers or any other element of a different data type, it will throw an error.

To understand this point, consider the example given below:

#include <stdio.h>
int main()
{
    // such declaration will throw
    // Compilation Error
    int my_array[6] = {1, 2, "mango", 4, 5, 6.2};
    int i;
    printf("Elements of the array are: ");
    for (i = 0; i < 6; i++)
    {
        printf("%d ", my_array[i]);
    } 
    return 0;
}

Output of the above example

Elements of the array are: 1 2 1040044036 4 5 6
jdoodle.c: In function ‘main’:
jdoodle.c:11:30: warning: initialization of ‘int’ from ‘char *’ makes integer from pointer without a cast [-Wint-conversion]
11 | int my_array[6] = {1, 2, “mango”, 4, 5, 6.2};
| ^~~
jdoodle.c:11:30: note: (near initialization for ‘my_array[2]’)

The array’s data type in the example above is int. However, a compilation error is thrown when we attempt to specify string and float values in the array.

By designing a structure to store heterogeneous (non-homogeneous) values, this problem can be overcome.

To grasp this idea, consider the example below:

#include <stdio.h>
// create a structure
struct example
{
    int array_quant;
    float array_rate;
    char array_name[30];
};
 int main()
{
    // s1 - object of the structure
    struct example num1 = {10, 90.45, "Arrays in C"};
    // accessing structure members
    // using structure object
    printf("%d\n", num1.array_quant);
    printf("%f\n", num1.array_rate);
    int x;
    for (x = 0; num1.array_name[x] != '\0'; x++)
    {
        printf("%c", num1.array_name[x]);
    }
    return 0;
}

Output of the above example

10
90.449997
Arrays in C

You can try to test here the example above!

Examples of the 1-D Array in C

The programs listed below show how to declare variables, initialize variables, perform input/output operations, and perform fundamental C operations like insertion, deletion, sorting, and searching in a 1-D array.

Example 1: Array Declaration, Input, and Output

#include <stdio.h>
int main()
{
    // declare an array.
    int my_array[6];
    printf("Enter array elements:\n"); 
    // input array elements.
    int x;
    for (x = 0; x < 6; x++)
    {
        scanf("%d", &my_array[x]);
    } 
    printf("\nArray elements are:\n");
    // print array elements.
    for (x = 0; x <= 5; x++)
    {
        printf("%d ", my_array[x]);
    }
    return 0;
}

Output of the above example

Array elements are:
0 0 1968791664 21941 40946032 32765

An integer array of size 6 is declared in the example above. There are a maximum of 6 integer entries in this array. The user inputs the array components into a “for loop.” Similar to that, these parts are printed in the output using a “for loop.” The loop iterates through every element of the array twice, from 0 to 5.

You can try to test here the example above!

Example 2: Insertion and Deletion in an Array.

#include <stdio.h>
int main()
{
    int x;
    // initialize an array.
    int array_elements[10] = {11, 6, 10, 50, 32, 56, 15, 98, 43, 22}; 
    // input index where the element is to be inserted.
    int position;
    printf("Enter the position:");
    scanf("%d", &position); 
    // input the element to be inserted. 
    int element;
    printf("Enter the element:");
    scanf("%d", &element); 
    if (position > 10)
    {
        printf("Input is invalid !");
    }
    else
    {   
        // right shifting array elements.
        for (x = 9; x >= position - 1; x--)
            array_elements[x + 1] = array_elements[x];
        // insert the element at "pos".
        array_elements[position - 1] = element;
        printf("Array after insertion is:\n");
        // print array elements.
        for (x = 0; x <= 10; x++)
            printf("% d ", array_elements[x]);
    }
    return 0;
}

Output of the above example

Enter the position: 5
Enter the element:100
Array after insertion is:
11, 6, 10, 50, 32, 56, 15, 98, 43, 22

An element that has to be introduced is used as input in the example above. Also included as input is the location in which this element is to be kept. To make room for the new element, the array elements are moved to the right. The array’s size is increased after insertion.

Example 3: Search an Element in the Array

#include <stdio.h>
int main()
{
    int x, element;
    // initialize an array.
    int array_elements[10] = {11, 6, 10, 50, 32, 56, 15, 98, 43, 22};
    printf("Enter element to be searched:\n");
    // input element to be searched.
    scanf("%d", &element); 
    // traverse the array to search the element.
    for (x = 0; x <= 9; x++)
    {
        if (array_elements[x] == element)
        {
            // print the index at which 
            // the element is found.
            printf("Element found at index %d", x);
            break;
        }
    } 
    // if the element is not found.
    if (x == 10)
    {
        printf("\nElement not found!");
    } 
    return 0;
}

Output of the above example

Enter element to be searched:
Element found at index 4

The user’s input for an element is used in the example above. By comparing each array element with the element to be searched, the array is traversed to do a linear search for this element. The “for loop” is ended and the element’s index is printed if it exists. If the element is absent, the “for loop” iterates from 0 to 9 without interruption, with I equal to 10 in that case.

You can try to test here the example above!

Example 4: Sorting Elements of an Array

#include <stdio.h>
int main()
{
    int x, y, temp;
    // initialize an array.
    int elements_array[10] = {11, 6, 10, 50, 32, 56, 15, 98, 43, 22}; 
    // print unsorted array.
    printf("Original array is: \n");
    for (x = 0; x < 10; x++)
    {
        printf("%d ", elements_array[x]);
    } 
    // sort the array elements in descending order.
    for (x = 0; x < 10; x++)
    {
        for (y = x + 1; y < 10; y++)
        {
            if (elements_array[y] > elements_array[x])
            {
                temp = elements_array[x];
                elements_array[x] = elements_array[y];
                elements_array[y] = temp;
            }
        }
    } 
    // print the sorted elements.
    printf("\n\nSorted array in descending order is: \n");
    for (x = 0; x < 10; x++)
    {
        printf("%d ", elements_array[x]);
    }
    return 0;
}

Output of the above example

Original array is:
11 6 10 50 32 56 15 98 43 22

Sorted array in descending order is:
98 56 50 43 32 22 15 11 10 6

In the example above, a 10-dimensional array is initialized. The bubble sort technique is used to arrange the array’s elements in decreasing order.

You can try to test here the example above!

Example 5: Finding the Largest and the Smallest Element in a 1-D Array in C

#include<stdio.h>
int main()
{
    // declare the array
    int array_elements[10] = {11, 6, 10, 50, 32, 56, 15, 98, 43, 22};
    int x, smallest, largest; 
    // assign the value of first array element 
    // to smallest and largest.
    smallest = largest = array_elements[0];
    // traverse the array.
    for(x = 0; x < 10; x++)
    {
        // if current element is larger than largest,
        // then update the value of largest.
        if(array_elements[x] > largest)
        {
            largest = array_elements[x];
        } 
        // if current element is smaller than smallest,
        // then update the value of smallest.
        if(array_elements[x] < smallest)
        {
            smallest = array_elements[x];
        }
     } 
    // print the smallest and the largest element.
    printf("The smallest element in the array is: %d", smallest);
    printf("\nThe largest element in the array is: %d", largest);
    printf("\n\n");
    return 0;
}

Output of the above example

The smallest element in the array is: 6
The largest element in the array is: 98

The largest and smallest element in an unsorted array are reported in the program above. The findings are stored in the two variables greatest and smallest. The first components of the array are used to initialize these variables. The largest and smallest elements are compared with each other while the array is linearly traversed, and their values are updated if a new greatest or smallest member is discovered.

You can try to test here the example above!

2 Dimensional Array in C

2-dimensional array in C is the most basic type of multi-dimensional array in C programming, sometimes known as a 2-D array. A distinct 1-D array can be used to represent each element of a 2-D array.

A 2-D array has a specific number of rows and columns, and multiplying the rows and columns yields the total number of array elements. The array has a total of 6 elements, for instance, if its format is my array[2][3].

When the number of rows and columns in a matrix is the same, the matrix is said to be square. The matrix is referred to as a rectangle matrix when the number of rows and columns differ.

A nested loop is required to handle a 2-D array. The inner loop denotes the column of elements in each row, whereas the outer loop denotes the number of rows.

However, depending on whether the user wants a row order matrix or a column order matrix, the relevance of the outer and inner loops can be modified.

Declaration of 2-D Array in C

Syntax to Declare a 2-Dimensional Array in C:

// declaring a 2-d array
dataType arrayName[no_of_rows][no_of_columns];

Description of the syntax:

  • dataType: This data type describes the kind of elements that will be stored in the array. It could be a char, int, float, or double.
  • arrayName: This is the array’s name. You must adhere to the same restrictions that apply when declaring a regular variable in C when specifying the name of an array.
  • no_of_rows: The array’s first dimension is the number of rows. It is an integer that specifies how many rows the array will hold.
  • no_of_columns: This is the array’s second dimension. It is an integer value that represents the array’s column count.

For Example

/ 5 x 10 matrix.
int my_array1[5][10];
// 3 x 3 square matrix.
float my_array2[3][3];
// 2 x 1 matrix.
char my_array3[2][1];  

The array can have a maximum of (no of rows * no of columns) elements in total. An array like arr[2][4] can only contain a maximum of 8 elements.

Initialization of 2-D Array in C

In 1-D arrays, you can omit the size specification when an array is initialized at the time of its declaration. With 2-D arrays, the situation is different. The first dimension is the only one that can be omitted, and the second dimension must be initialized.

A 2-D array in C can be initialized in the ways shown below:

  • Conventional way: 1-D arrays with elements equal to the number of the second dimension are formed by multiplying the number of rows in the array by the number of the first dimension (or columns) (or columns).

For Example

int my_array[3][2] = {
    {11, 12},
    {21, 22},
    {31, 32}
}; 

In the aforementioned example, there are 3 1-D arrays with 2 elements each (3 = number of rows; 2 = number of columns).

  • The compact method involves writing all array components on the same line, separated by commas. It appears to be the startup of a 1-D array. Since the initialized array is less readable, this approach is not advised.

For Example

int array_element[3][2] = {11, 12, 21, 22, 31, 32};

All of the array items in the aforementioned example are written between a single set of braces, or “.” Less readable initializations like this one.

  • Using a loop: 2-D arrays can also be initialized using a loop, just as 1-D arrays. The “for loop” is the most widely used loop. The array has to be initialized using two nested loops.

For Example

int array_element[2][3];
int i, j;
// The first loop runs till the number of rows.
for(i = 0; i < 2; i++) 
{
  // second loop runs till number of columns.
  for (j = 0; j < 3; j++)
  {
    array_element[i][j] = i + j;
  }
}
/* array_element= {
                {0, 1, 2},        
                {1, 2, 3}
              } */

Two “for loops” are used to initialize a 2-D array in the example above. The first loop goes from 0 to however many rows there are. And the second loop goes from 0 to whichever many columns there are.

Points to Remember While 2-D Array Initialization

When declaring a 2-D array, the first dimension can be optional, but the second dimension is required. The potential blunders that might be made when initializing a 2-D array in C are shown by the following examples:

// valid
int array_element[3][3] = {10, 20, 30 ,40, 50, 60, 70, 70, 80, 90}
// valid 
int array_element[][3] = {10, 20, 30 ,40, 50, 60, 70, 70, 80, 90}  
// invalid: second dimension must be specified.
int array_element[][] = {10, 20, 30 ,40, 50, 60, 70, 70, 80, 90}   
// invalid: second dimension must be specified.
int array_element[3][] = {10, 20, 30 ,40, 50, 60, 70, 70, 80, 90}

Examples of 2-D Array in C

The basic operations of a 2-D array, such as calculating a matrix’s transpose and performing input and output operations in a 2-D matrix, are illustrated by the examples that follow.

Example 1: 2-D Array Declaration, Input, and Output.

#include <stdio.h>
int main()
{
    // declaring and initializing the 2-D array.
    // 2-D array with 5 rows and 2 columns.
    int x[5][2] = {{0, 1}, {2, 3}, {4, 5}, {6, 7}, {8, 9}};
    int a, b; 
    // print the value of each array element. 
    // outer loop- for rows.
    for (a = 0; a < 5; a++)
    {
        // inner loop- for columns.
        for (b = 0; b < 2; b++)
        {
            printf("Element at the Value of x[ %d", a);
            printf("][ %d", b);
            printf("] :");
            printf("%d", x[a][b]);
            printf("\n");
        }
    }
    return 0;
}

Output of the above example

Element at the Value of x[ 0][ 0] :0
Element at the Value of x[ 0][ 1] :1
Element at the Value of x[ 1][ 0] :2
Element at the Value of x[ 1][ 1] :3
Element at the Value of x[ 2][ 0] :4
Element at the Value of x[ 2][ 1] :5
Element at the Value of x[ 3][ 0] :6
Element at the Value of x[ 3][ 1] :7
Element at the Value of x[ 4][ 0] :8
Element at the Value of x[ 4][ 1] :9

A 2-D array with 5 rows and 2 columns has been declared and initialized in the example below. We are using two “for loops” to print. While the inner “for loop” prints columns for each row, the outer “for loop” prints the rows.

You can try to test here the example above!

Example 2: Finding Sum and Product of Two 2 Matrices

#include <stdio.h>
int main()
{
    // declaring arr1 and arr2.
    int arr1[2][2], arr2[2][2];
    int sum[2][2], product[2][2]; 
    // reading input for arr1 from the user.
    printf("Enter the elements of arr1 : \n");
    for (int i = 0; i < 2; i++)
    {
        for (int j = 0; j < 2; j++)
        {
            printf("arr1[%d][%d] :", i, j);
            scanf("%d", &arr1[i][j]);
        }
        printf("\n");
    } 
    // reading input for arr2 from the user.
    printf("Enter the elements of arr2: \n");
    for (int i = 0; i < 2; i++)
    {
        for (int j = 0; j < 2; j++)
        {
            printf("arr2[%d][%d] :", i, j);
            scanf("%d", &arr2[i][j]);
        }
        printf("\n");
    } 
    // adding the corresponding array elements.
    printf("Sum array is : \n");
    for (int i = 0; i < 2; i++)
    {
        for (int j = 0; j < 2; j++)
        {
            sum[i][j] = arr1[i][j] + arr2[i][j]; 
            //print the sum array
            printf("%d\t", sum[i][j]);
        }
        printf("\n");
    }
    // multiplying the corresponding array elements.
    printf("Product array is : \n");
    for (int i = 0; i < 2; i++)
    {
        for (int j = 0; j < 2; j++)
        {
            product[i][j] = arr1[i][j] * arr2[i][j]; 
            // print the product array.
            printf("%d\t", product[i][j]);
        }
        printf("\n");
    }
    return 0;
}

Output of the above example

Enter the elements of arr1 :
arr1[0][0] :arr1[0][1] :
arr1[1][0] :arr1[1][1] :
Enter the elements of arr2:
arr2[0][0] :arr2[0][1] :
arr2[1][0] :arr2[1][1] :
Sum array is :
0 0
-1852033923 21952
Product array is :
0 0
0 0

The number of rows and columns in both matrices must match in order to calculate the addition of the two matrices. The number of columns in the first matrix should match the number of rows in the second matrix in order to calculate their product.

A resultant matrix with the same order is declared in order to obtain the total of the two matrices. A resultant matrix with rows equal to the first matrix and columns equal to the second matrix is declared in order to obtain the product of the two matrices.

You can try to test here the example above!

Arrays vs. Pointers

In a variety of situations, such as when an array is handed to a function, it can behave as a pointer. Arrays can use pointer arithmetic as well. These two, however, are very different from one another. The fundamental distinctions between a pointer and an array in C are outlined in the comparison table below.

COMPARISON BASISARRAYPOINTER
DEFINITIONAn array stores one or more values of a similar type. A pointer stores the address or memory location of a variable.
SYNTAXtype array_name[size];Type *ptr_name;
MEMORY ALLOCATIONContiguous or sequential memory is allocated to the elements of an array.A pointer can be allocated to any random available memory.
MEMORY SPACEArrays are static, so their size cannot be altered.A pointer is dynamic, so the memory size can be either altered or even freed.
NO. OF VALUES STOREDA single array can store a large number of elements.A pointer can point to only one variable’s address.
TYPEThe data type of the array is determined by the type of elements stored in it.The data type of a pointer is determined by the type of the variable whose memory location it is pointing to.
Sizeof() OperatorWhen an array is passed to the sizeof() operator, the combined size of all the stored elements is returned.When a pointer is passed to the sizeof() operator, the size of the pointer is printed (generally 8). This size is the same for any type of pointer.
COMPILE-TIME/ RUN-TIMEMemory is allocated to an array during the compilation. Memory is allocated to a pointer during the run time of the program.

Summary

In conclusion, you have learned about the C array notion in this tutorial. You began with a brief overview of the array data structure before gradually moving on to talk about the use, benefits, and drawbacks of arrays. The various techniques to declare and initialize arrays in C were then covered.

The accessing of array elements as well as elements entering or leaving an array came next. You later saw some illustrations of 1D and 2D arrays. You also learned about pointers to an array, how to pass an array to a function, and the distinctions between an array and a pointer.

About Next Tutorial

In the next following post, I’ll create a Pointers in C and try to explain its many components in full details. I hope you enjoy this post on Array in C – What is array in C Programming Language, in which I attempt to illustrate the language’s core grammar.

Leave a Comment