• Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

C array declaration and assignment?

I've asked a similar question on structs here but I'm trying to figure out how C handles things like assigning variables and why it isn't allowed to assign them to eachother if they are functionally the same.

Lets say I have two arrays:

Why won't x = y compile? If they are both the same "signature" like that, then shouldn't you be able to assign them back and forth?

Can I declare these in a way that would allow me to do that in C? It makes sense to me that you would be able to, but maybe there is a way that this can be done? Typedefs for structs seemed to be the solution, would it be the same for array declaration and assignment?

I appreciate your guys help, I'm new to Stackoverflow but it has been a really good resource for me so far!

Community's user avatar

7 Answers 7

Simply put, arrays are not assignable. They are a "non-modifiable lvalue". This of course begs the question: why? Please refer to this question for more information:

Why does C++ support memberwise assignment of arrays within structs, but not generally?

Arrays are not pointers. x here does refer to an array, though in many circumstances this "decays" (is implicitly converted) to a pointer to its first element. Likewise, y too is the name of an array, not a pointer.

You can do array assignment within structs:

But you can't do it directly with arrays. Use memcpy .

Jakob's user avatar

This compiles and y will be the same as x .

Stephan's user avatar

Some messages here say that the name of an array yields the address of its first element. It's not always true:

Bastien Léonard's user avatar

In order to assign arrays you will have to assign the values inside the array.

ie. x=y is equivalent to

aJ.'s user avatar

In an attempt to complement Blank's answer, I devised the following program:

When executed, the following is output:

The point is to illustrate how the copy of structures' values occurs.

David's user avatar

When saying "int x[10]" is saying, "reserve some room for 10 integers and pass me a pointer to the location". So for the copy to make sense you'd need to operate on the memory pointed by, rather than 'the name of the memory location'.

So for copying here you'd use a for loop or memcpy().

amo-ej1's user avatar

I've used C compilers where that would compile just fine...and when run the code would make x point to y's array.

You see, in C the name of an array is a pointer that points to the start of the array. In fact, arrays and pointers are essentially interchangable. You can take any pointer and index it like an array.

Back when C was being developed in the early 70's, it was meant for relatively small programs that were barely above assembly language in abstraction. In that environment, it was damn handy to be able to easily go back and forth between array indexing and pointer math. Copying whole arrays of data, on the other hand, was a very expensive thing do do, and hardly something to be encouraged or abstracted away from the user.

Yes, in these modern times it would make way more sense to have the name of the array be shorthand for "the whole array", rather than for "a ponter to the front of the array". However, C wasn't designed in these modern times. If you want a language that was, try Ada. x := y there does exactly what you would expect; it copies one array's contents to the other.

T.E.D.'s user avatar

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged c arrays variable-assignment or ask your own question .

Hot Network Questions

array assignment in c

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

CProgramming Tutorial

Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

Arrays in C

Declaring Arrays

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows −

This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type. For example, to declare a 10-element array called balance of type double, use this statement −

Here balance is a variable array which is sufficient to hold up to 10 double numbers.

Initializing Arrays

You can initialize an array in C either one by one or using a single statement as follows −

The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ].

If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write −

You will create exactly the same array as you did in the previous example. Following is an example to assign a single element of the array −

The above statement assigns the 5 th element in the array with a value of 50.0. All arrays have 0 as the index of their first element which is also called the base index and the last index of an array will be total size of the array minus 1. Shown below is the pictorial representation of the array we discussed above −

Array Presentation

Accessing Array Elements

An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example −

The above statement will take the 10 th element from the array and assign the value to salary variable. The following example Shows how to use all the three above mentioned concepts viz. declaration, assignment, and accessing arrays −

When the above code is compiled and executed, it produces the following result −

Arrays in Detail

Arrays are important to C and should need a lot more attention. The following important concepts related to array should be clear to a C programmer −

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Arrays (C# Programming Guide)

You can store multiple variables of the same type in an array data structure. You declare an array by specifying the type of its elements. If you want the array to store elements of any type, you can specify object as its type. In the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object .

The following example creates single-dimensional, multidimensional, and jagged arrays:

Array overview

An array has the following properties:

Default value behaviour

Arrays as Objects

In C#, arrays are actually objects, and not just addressable regions of contiguous memory as in C and C++. Array is the abstract base type of all array types. You can use the properties and other class members that Array has. An example of this is using the Length property to get the length of an array. The following code assigns the length of the numbers array, which is 5 , to a variable called lengthOfNumbers :

The Array class provides many other useful methods and properties for sorting, searching, and copying arrays. The following example uses the Rank property to display the number of dimensions of an array.

For more information, see the C# Language Specification . The language specification is the definitive source for C# syntax and usage.

Submit and view feedback for

Additional resources

Trending now

.net developer job description, 10 best javascript books for 2023, blockchain career guide: a comprehensive playbook to becoming a blockchain developer, top css interview questions you should prepare for in 2023, top 12 uses of c++, top 10 python ides in 2023: choosing the best one, 20 most popular programming languages to learn in 2023, list to string in python, create a blockchain career with the iit kanpur professional certificate program, top 50+ salesforce interview questions and answers for 2023, array in c: definition, advantages, declare, initialize and more.

Array in C

Table of Contents

Array in C can be defined as a method of clubbing multiple entities of similar type into a larger group. These entities or elements can be of int, float, char, or double data type or can be of user-defined data types too like structures. However, in order to be stored together in a single array, all the elements should be of the same data type .  The elements are stored from left to right with the left-most index being the 0th index and the rightmost index being the (n-1) index. 

Basics to Advanced - Learn It All!

Basics to Advanced - Learn It All!

Array  in C are of two types; Single dimensional arrays and Multidimensional arrays.

array_in_C_1

array_in_C_2

Why Do We Need Arrays?

If we have a small number of elements, let us say we want 3 variables, then we can declare them separately like var1, var2, and var3. But if we have a large number of variables then we can use arrays to store them. 

Let us take a real-life example. Suppose you want to make a program that prints 1-100 digits. Now in C language, you can achieve this by 2 methods. The first one is to make 100 variables and store the numbers from 1-100 in those variables separately and then print each digit. The second method is to create an array of size 100 and store the numbers in that array using a loop. These digits can be printed using a single loop in linear complexity. It is clear that the second method is more optimized and desirable than the first one as it is more convenient to store these values in a single array rather than creating 100 variables.

Learn the Ins & Outs of Software Development

Learn the Ins & Outs of Software Development

Declaration and Initialization of Array in C

There are various ways in which an array can be declared and initialized in various ways. You can declare an array of any data type (i.e. int, float, double, char) in C. The following ways can be used to declare and initialize an array in C. 

Array Declaration by Specifying the Size

Arrays can be declared by specifying the size or the number of array elements. The size of the array specifies the maximum number of elements that the array can hold. In the latest version of C, you can either declare an array by simply specifying the size at the time of the declaration or you can provide a user-specified size. The following syntax can be used to declare an array simply by specifying its size.

Image Reference 

When an array is declared without allocating any value, then it stores a garbage value. If you access any uninitialized array value, then just like any uninitialized variable, it will give you a garbage value. 

Learn from the Best in the Industry!

Learn from the Best in the Industry!

Array Declaration by Initializing Elements

An array can be initialized at the time of its declaration. In this method of array declaration, the compiler will allocate an array of size equal to the number of the array elements. The following syntax can be used to declare and initialize an array at the same time.

// initialize an array at the time of declaration.

int my_array[] = {100, 200, 300, 400, 500}

In the above syntax, an array of 5 elements is created and even though the array size has not been specified here, the compiler will allocate a size of 5 integer elements.

Array Declaration by Specifying the Size and Initializing Elements

An array can also be created by specifying the size and assigning array elements at the time of declaration. This method of array creation is different from the previous one. Here, if the number of initialized elements is less than the size of the array specified, then the rest of the elements will automatically be initialized to 0 by the compiler. See the following syntax to understand this.

// 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}

In the above array syntax, my_array1 is an array of size 5 with all five elements initialized. Whereas, my_array2 is an array of size 5 with only three of its elements initialized. The remaining two elements of the second array will be initialized to 0 by the compiler.

Here's How to Land a Top Software Developer Job

Here's How to Land a Top Software Developer Job

Array Initialization Using a Loop

An array can also be initialized using a loop. The loop iterates from 0 to (size - 1) for accessing all indices of the array starting from 0. The following syntax uses a “for loop” to initialize the array elements. This is the most common way to initialize an array in C.

// declare an array.

int my_array[5];

// initialize array using a "for" loop.

for(i = 0; i < 5; i++) 

    my_array[i] = 2 * i;

// my_array = {0, 2, 4, 6, 8}  

In the above syntax, an array of size 5 is declared first. The array is then initialized using a for loop that iterates over the array starting from index 0 to (size - 1).

Access Array Elements

Since an array is stored contiguously in the memory, it has indices starting from ”0” to “array_size - 1”, also known as zero-based indexing. This indexing represents the position in the array.

The array indices are used to access any element of the array in the following way:

array_name[index]

The index of the element to be accessed is specified within square brackets “[]”. The range of the index is- integers in the range [0, size).

int my_array[6]; 

// access 1st element

my_array[0] = 100;

// access 4th element

my_array[2] = 300;

// access last element

my_array[5] = 600;

Get All Your Questions Answered Here!

Get All Your Questions Answered Here!

Input and Output Array Elements

Array values can be stored by taking input from the user and storing them in the array. The following example illustrates 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]);

Similarly, array elements can also be displayed in the output using the printf() method. The index is specified indicating the position of the element to be printed. The following example illustrates 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

Arrays have a great significance in the C language. They provide several advantages to the programmers while programming. Some of them are:

Also Read: Difference Between Coding and Programming

Create and Showcase Your Portfolio from Scratch!

Create and Showcase Your Portfolio from Scratch!

Disadvantages of Array in C

Every advantageous thing comes with some disadvantages as well. This stands true for arrays as well. Below are some of the disadvantages of the array in C:

#include <stdio.h>

    //declaring the array of size 20

    int my_array[20];

    //initialising the array elements

    for (int i = 0; i < 20; i++)

        //i will be the value of e

        //very ith element of the array

        my_array[i] = i;

    // 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"

           my_array[13]);

    // Print value at index 21 of the array

    printf("Element at index 21"

           " is %d",

           my_array[21]);

    return 0;

array_in_C_3.

Become a Skilled Web Developer in Just 9 Months!

Become a Skilled Web Developer in Just 9 Months!

In the above example, the initial value of the array arr is 20, so by printing the value of elements up to the index 20, we are getting the desired output. But when we try to print the element at the 21st index, it is giving a garbage value. This is because the array was accessed out of the bound index.

This issue can be resolved using malloc() and calloc() functions. These functions allocate the memory dynamically. We have a free() function that allows us to free the unwanted memory at our will. The below example illustrates the same:

#include <stdlib.h>

    //*ptr will be storing the base

    //address of the array elements

    int *ptr;

    int size, i;

    // size of the array will be 5

    size = 5;

    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);

        // Memory has been successfully allocated

        printf("Memory has been allocated successfully\n");

        // initializing the array elements

        for (i = 0; i < size; ++i)

            ptr[i] = i + 1;

        // Print the elements of the array

        printf("The elements of the array are: ");

            printf("%d ", ptr[i]);

array_in_C_4.

    // such declaration will throw

    // Compilation Error

    int my_array[6] = {1, 2, "mango", 4, 5, 6.2};

    printf("Elements of the array are: ");

    for (i = 0; i < 6; i++)

        printf("%d ", my_array[i]);

array_in_C_5.

In the above example, the data type of the array is int. But when we try to declare string and float values to the array, it throws a compilation error. 

This issue can be resolved by creating a structure to store heterogeneous (non-homogeneous) values. Consider the below example to understand this concept:

// create a structure

struct example

    int fruit_quant;

    float fruit_rate;

    char fruit_name[30];

 int main()

    // s1 - object of the structure

    struct example s1 = {10, 90.45, "Mango"};

    // accessing structure members

    // using structure object

    printf("%d\n", s1.fruit_quant);

    printf("%f\n", s1.fruit_rate);

    for (i = 0; s1.fruit_name[i] != '\0'; i++)

        printf("%c", s1.fruit_name[i]);

array_in_C_6.

Examples of the 1-D Array in C

The following programs illustrate declaration, initialization, input/output operations, and basic operations like insertion,  deletion, sorting, and searching in the 1-D array in C. 

Example 1: Array Declaration, Input, and Output

    // declare an array.

    int my_array[6];

    printf("Enter array elements:\n"); 

    // input array elements.

        scanf("%d", &my_array[i]);

    printf("\nArray elements are:\n");

    // print array elements.

    for (i = 0; i <= 5; i++)

array_in_C_7.

In the above example, an integer array of size 6 is declared. This array can hold at most 6 integer elements. A “for loop” is used to input the array elements from the user. Similarly, a “for loop” is used to print these elements in the output. Both times the loop runs from 0 to 5, to iterate over all the array elements.

Example 2: Insertion and Deletion in an Array.

    // initialize an array.

    int my_array[10] = {11, 6, 10, 50, 32, 56, 15, 98, 43, 22}; 

    // input index where the element is to be inserted.

    int pos;

    printf("Enter the position: ");

    scanf("%d", &pos); 

    // input the element to be inserted. 

    int element;

    printf("Enter the element: ");

    scanf("%d", &element); 

    if (pos > 10)

        printf("Input is invalid !");

        // right shifting array elements.

        for (i = 9; i >= pos - 1; i--)

            my_array[i + 1] = my_array[i];

        // insert the element at "pos".

        my_array[pos - 1] = element;

        printf("Array after insertion is:\n");

        // print array elements.

        for (i = 0; i <= 10; i++)

            printf("% d ", my_array[i]);

array_in_C_8

In the above example, an element that needs to be inserted is taken as input. The position where this element is to be stored is also taken as input. The array elements are shifted to the right to make space for the new element. After insertion, the size of the array is incremented.

Example 3: Search an Element in the Array.

    int i, element;

    int my_array[10] = {11, 6, 10, 50, 32, 56, 15, 98, 43, 22};

    printf("Enter element to be searched:\n");

    // input element to be searched.

    // traverse the array to search the element.

    for (i = 0; i <= 9; i++)

        if (my_array[i] == element)

            // print the index at which 

            // the element is found.

            printf("Element found at index %d", i);

            break;

    // if the element is not found.

    if (i == 10)

        printf("\nElement not found!");

array_in_C_9

In the above example, an element is taken as input from the user. The array is traversed to search this element linearly by comparing all array elements with the element to be found. If the element exists, then its index is printed and the “for loop” is exited. If the element does not exist, then the “for loop” is iterated interrupted from 0 to 9, and “i” will be equal to 10. 

Example 4: Sorting Elements of an Array

    int i, j, temp;

    // print unsorted array.

    printf("Original array is: \n");

    for (i = 0; i < 10; i++)

    // sort the array elements in descending order.

        for (j = i + 1; j < 10; j++)

            if (my_array[j] > my_array[i])

            {

                temp = my_array[i];

                my_array[i] = my_array[j];

                my_array[j] = temp;

            }

    // print the sorted elements.

    printf("\n\nSorted array in descending order is: \n");

array_in_C_10.

In the above example, an array of size 10 is initialized. The array elements are sorted in descending order using the bubble sort algorithm.  

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

#include<stdio.h>

    // declare the array

    int i, smallest, largest; 

    // assign the value of first array element 

    // to smallest and largest.

    smallest = largest = my_array[0];

    // traverse the array.

    for(i = 0; i < 10; i++)

        // if current element is larger than largest,

        // then update the value of largest.

        if(my_array[i] > largest)

            largest = my_array[i];

        // if current element is smaller than smallest,

        // then update the value of smallest.

        if(my_array[i] < smallest)

            smallest = my_array[i];

    // 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");

array_in_C_11

In the above program, the largest and the smallest element in an unsorted array is printed. The two variables largest and smallest are created to store the results. These variables are initialized to the first array elements. The array is traversed linearly and each element is compared with the current largest and smallest, and their values are updated if a new largest or smallest element is found.

2 Dimensional Array in C

array_in_C_12

A 2-dimensional array or 2-D array is the simplest form of multi-dimensional array in C. Each element in a 2-D array can be represented as a separate 1-D array. A 2-D array contains a certain number of rows and columns and the total number of array elements can be found by multiplying the number of rows and columns. For example, if the array is my_array[2][3], then the total number of elements in the array is 6.

A matrix is said to be a square matrix when the number of rows is equal to the number of columns. When the number of rows differs from the number of columns, the matrix is said to be a rectangle matrix. Processing a 2-D array requires a nested loop. The outer loop signifies the number of rows and the inner loop signifies the column of elements of each row. However, the significance of the outer and inner loops can be interchanged depending on whether the user wants a row order matrix or a column order matrix.

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:

// 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];  

Note: The total number of elements that the array can hold is (no_of_rows * no_of_columns). For example, an array arr[2][4] can have at most 8 elements.

Initialization of 2-D Array in C

In 1-D arrays, when an array is initialized at the time of its declaration, you can skip specifying its size. However, this scenario is different with 2-D arrays. Only the first dimension can be skipped and the second dimension is mandatory at the time of initialization. 

The following ways can be used to initialize a 2-D array in C:

int my_array[3][2] = {

    {11, 12},

    {21, 22},

    {31, 32}

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

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

In the above example, all array elements are written inside a single pair of braces “{}”. This type of initialization is less readable.  

int my_array[2][3];

// 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++)

    my_array[i][j] = i + j;

/* my_array = {

                {0, 1, 2},        

                {1, 2, 3}

              } */

In the above example, two “for loops” are used to initialize a 2-D array. The first loop runs from 0 to the number of rows. And the second loop runs from 0 to the number of columns.

Points to Remember While 2-D Array Initialization

The second dimension is mandatory while declaring a 2-D array, whereas the first dimension can be optional. The following examples illustrate the possible mistakes that can be made while initializing a 2-D array in C: 

int my_array[3][3] = {10, 20, 30 ,40, 50, 60, 70, 70, 80, 90}

int my_array[][3] = {10, 20, 30 ,40, 50, 60, 70, 70, 80, 90}  

// invalid: second dimension must be specified.

int my_array[][] = {10, 20, 30 ,40, 50, 60, 70, 70, 80, 90}   

int my_array[3][] = {10, 20, 30 ,40, 50, 60, 70, 70, 80, 90}

Examples of 2-D Array in C

The following examples illustrate the basic implementation of a 2-D array including input and output operations in a 2-D matrix and finding the transpose of a matrix. 

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

    // 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 i, j; 

    // print the value of each array element. 

    // outer loop- for rows.

    for (i = 0; i < 5; i++)

        // inner loop- for columns.

        for (j = 0; j < 2; j++)

            printf("Element at x[ %d", i);

            printf("][ %d", j);

            printf("] :");

            printf("%d", x[i][j]);

            printf("\n");

array_in_C_13.

In the following example, a 2-D array of 5 rows and 2 columns has been declared and initialized. For printing, we are using two “for loops”. The outer “for loop” is printing the rows while the inner “for loop” is printing columns for every row.

Example 2: Finding Sum and Product of Two 2 Matrices

    // 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");

            printf("arr2[%d][%d] :", i, j);

            scanf("%d", &arr2[i][j]);

    // adding the corresponding array elements.

    printf("Sum array is : \n");

            sum[i][j] = arr1[i][j] + arr2[i][j]; 

            //print the sum array

            printf("%d\t", sum[i][j]);

    // multiplying the corresponding array elements.

    printf("Product array is : \n");

            product[i][j] = arr1[i][j] * arr2[i][j]; 

            // print the product array.

            printf("%d\t", product[i][j]);

array_in_C_14

For finding the addition of two matrices, the number of rows and columns should be the same in both the matrices. And for finding the product of two matrices, the number of columns in the first matrix should be the same as the number of rows in the second matrix.

To get the sum of the two matrices, a resultant matrix of the same order is declared. To get the product of the two matrices, a resultant matrix having rows equal to the first matrix and columns equal to the second matrix is declared. 

Example 3: Transpose of a Matrix

Square matrix.

    // declaring the matrices.

    int arr[10][10], transpose[10][10];   

    // reading the input from the user.

    printf("Enter elements of the arr\n");

            scanf("%d", &arr[i][j]); 

    // copy the array element into another element.

            transpose[j][i] = arr[i][j];

    printf("Transpose of the arr:\n");

    //print the transpose of the arr

            printf("%d\t", transpose[i][j]);

array_in_C_15

In the above example, the transpose of a square matrix is printed. For printing the transpose of the matrix, first, the matrix elements are copied in another matrix and then the rows and the columns of the copied matrix are reversed. 

Rectangular Matrix

    int arr[10][10], transpose[10][10];

        for (int j = 0; j < 3; j++)

            scanf("%d", &arr[i][j]);

    }        

    }       

    // print the transpose of the array.

    for (int i = 0; i < 3; i++)

array_in_C_16.

In the above example, the matrix is a rectangle matrix which means that the number of the rows is not equal to the number of the columns. The logic is the same as that in the previous example.

Example 4: Check if the Given Matrix is Sparse or Not

    int row, col, a[10][10], count = 0;

    // read the number of rows and columns from the user.

    printf("Enter the number of rows: \n");

    scanf("%d", &row);

    printf("Enter the number of columns: \n");

    scanf("%d", &col); 

    // read the elements of the matrix from the user.

    printf("Enter the matrix elements: \n");

    for (int i = 0; i < row; i++)

        for (int j = 0; j < col; j++)

            scanf("%d", &a[i][j]);

    // print the matrix.

    printf("Matrix is:\n");

            printf("%d\t", a[i][j]);

    // check if the matrix is sparse or not.

            if (a[i][j] == 0)

                count++;

    if (count > ((row * col) / 2))

        printf("Matrix is a sparse matrix \n");

        printf("Matrix is not sparse matrix\n");

array_in_C_17

In the above example, it is checked whether the matrix is sparse or not. A sparse matrix is the one in which the number of 0’s is greater than the non-zero elements. A counter is maintained to count the number of 0’s. At last, the count of 0’s is compared with half the total number of elements of the matrix. 

Arrays vs. Pointers

Arrays can behave like pointers in many circumstances such as when an array is passed to function, it is treated as a pointer. Also, pointer arithmetic is applicable to arrays. However, these two differ from each other in many ways. The following comparison chart summarizes the key differences between a pointer and an array in C.

Passing an Array to a Function

When an array in C is passed to a function, only the address of the array’s first element is passed to the function. And being contiguous in nature, the whole array can be accessed by the function using the address of the first element.

Passing an Array Element to a Function

We can pass a  single array element to a function as its argument. The following examples illustrate how we can pass an array element to a function. Here, we have made a function that is simply printing the element passed to it.

//function having an int type parameter

void func(int a)

    printf("Array element passed to the function is: %d", a);

    //initialized 1-D array

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

    //function call

    func(arr[2]);        //passing arr[2] i.e., 3 to the func.

array_in_C_18

Passing a 1-D Array to a Function

In the above section, we saw passing an array element to a function. In this section, we are going to have a look at how a 1-D array can be passed to a function through a simple example given below. Here a function has been made to which we are passing an array and its size and the function is returning the maximum element of that array.

// function find the greatest array element

int maximum(int arr[], int size)

    int large = arr[0];

    for(i = 0; i<size; i++)

        if(arr[i]>large)

            large = arr [i];

    return large;

    int result;

    // 1-D array initialization

    int arr[] = {100, 2, 1, 120, 55, 41};

    int size = sizeof(arr) / sizeof(int); 

    // function call

    result = maximum(arr, size);   // 1-D array is passed to the function. 

    printf("The greatest array element is: %d", result);

array_in_C_19.

Passing a Multidimensional Array to a Function

We can pass a matrix or a 2-D array to a matrix as well. The below example illustrates the same where a matrix is passed to a function and the function is printing that matrix.

// function to print the matrix elements

void printMatrix(int arr[3][3])

    int i, j;

    printf("The Matrix thus formed is: \n");

    for (i = 0; i < 3; ++i)

        // change the line

        for (j = 0; j < 3; ++j)

        {       

            printf("%d\t", arr[i][j]);

    int arr[3][3], i, j; 

    // reading input from user

    printf("Enter the elements: \n");

        {    

    // passing 2-D array or a 

    // Matrix as an argument

    printMatrix(arr);

array_in_C_20

Pointers to Array

As we have already discussed in the earlier section the relationship and difference between arrays and pointers in C. In this section, we are going to discuss how a pointer can be declared to store the address of an array. 

The following advantages are achieved by declaring a pointer to an array:

#include<stdio.h> 

  int my_array[8] = {10, 20, 30, 40, 50, 60, 70, 80}; 

  // declare a pointer pointing to the above array.

  int *my_ptr = my_array; 

  my_ptr = my_array;

  // access an array element using the pointer.

  *(my_ptr + 1) = 100; 

  // print array elements using the pointer.

   printf( "Array elements are: \n");    

   for ( i = 0; i < 8; i++ ) {

      printf("*(my_ptr + %d) = %d\n",  i, *(my_ptr + i) );

  return 0;

array_in_C_21

In the above program, a pointer *my_ptr is pointing to the array my_array. This simply means that the address of the array’s first element (i.e. my_array[0]) is stored in the pointer. The pointer now has access to all elements of the array.

That was all about Array in C

Final Thoughts!

To sum up, in this article you have learned the concept of array in C. You started with a brief introduction to the array data structure and gradually moved ahead to discuss the need, advantages, and disadvantages of arrays. Next, you saw the different ways to declare and initialize arrays in C.

Next, you learned how to access array elements and input or output elements to/from an array. Moving ahead, you saw some examples of 1D and 2D arrays. Finally, you learned how to pass an array to a function, a concept called pointers to an array, and the differences between an array and a pointer.

Why stop here? If you want to learn full-stack web development, you should definitely check out Simplilearn’s 9-month instructor-led certification training course on Full Stack Web Development. This will get you started in professional web development and you will be able to learn advanced concepts such as Agile methodologies, DevOps practices, Java and its frameworks such as Spring, Hibernate, etc., JS, CSS , HTML, etc. If you have a knack for learning new courses, you should definitely check out Simplilearn’s complete list of free courses.

If you have any queries in this “Array in C” article or suggestions for us, please mention them in the comment box and our experts answer them for you as soon as possible.

Happy Learning! 

Find our Post Graduate Program in Full Stack Web Development Online Bootcamp in top cities:

About the author.

Ravikiran A S

Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

Recommended Programs

Post Graduate Program in Full Stack Web Development

*Lifetime access to high-quality, self-paced e-learning content.

What is C Programming?

What is C Programming?

Recommended resources.

The Ultimate Guide to Top Front End and Back End Programming Languages for 2021

The Ultimate Guide to Top Front End and Back End Programming Languages for 2021

C# Programming for Beginners

C# Programming for Beginners

An Easy Guide To Understand The C++ Array

An Easy Guide To Understand The C++ Array

Combating the Global Talent Shortage Through Skill Development Programs

Combating the Global Talent Shortage Through Skill Development Programs

C Program for Prime Number

C Program for Prime Number

A One Stop Solution to Understand C# Arrays

A One Stop Solution to Understand C# Arrays

Related Articles

Array of Strings in C

In C programming String is a 1-D array of characters and is defined as an array of characters. But an array of strings in C is a two-dimensional array of character types. Each String is terminated with a null character (\0). It is an application of a 2d array.

Example: 

Below is the Representation of the above program 

We have 3 rows and 10 columns specified in our Array of String but because of prespecifying, the size of the array of strings the space consumption is high. So, to avoid high space consumption in our program we can use an Array of Pointers in C.

Invalid Operations in Arrays of Strings 

We can’t directly change or assign the values to an array of strings in C.

Here, arr[0] = “GFG”; // This will give an Error which says assignment to expression with an array type.

To change values we can use strcpy() function in C

Array of Pointers of Strings

In C we can use an Array of pointers. Instead of having a 2-Dimensional character array, we can have a single-dimensional array of Pointers. Here pointer to the first character of the string literal is stored.

Below is the C program to print an array of pointers:

Please Login to comment...

Improve your Coding Skills with Practice

Start your coding journey now.

Learn C++ interactively.

Learn C++ practically and Get Certified .

Popular Tutorials

Popular examples, reference materials.

Learn C++ Interactively

Interactive C++ Course

C++ introduction.

C++ Flow Control

C++ Arrays & String

C++ Object & Class

C++ Pointers and Arrays

Related Topics

C++ Multidimensional Arrays

C++ Ranged for Loop

In this tutorial, we will learn to work with arrays. We will learn to declare, initialize, and access array elements in C++ programming with the help of examples.

In C++, an array is a variable that can store multiple values of the same type. For example,

Suppose a class has 27 students, and we need to store the grades of all of them. Instead of creating 27 separate variables, we can simply create an array:

Here, grade is an array that can hold a maximum of 27 elements of double type.

In C++, the size and type of arrays cannot be changed after its declaration.

For example,

Access Elements in C++ Array

In C++, each element in an array is associated with a number. The number is known as an array index. We can access elements of an array by using those indices.

Consider the array x we have seen above.

C++ Array Declaration

Few Things to Remember:

C++ Array Initialization

In C++, it's possible to initialize an array during declaration. For example,

C++ Array Initialization

Another method to initialize array during declaration:

Here, we have not mentioned the size of the array. In such cases, the compiler automatically computes the size.

C++ Array With Empty Members

In C++, if an array has a size n , we can store upto n number of elements in the array. However, what will happen if we store less than n number of elements.

Here, the array x has a size of 6 . However, we have initialized it with only 3 elements.

In such cases, the compiler assigns random values to the remaining places. Oftentimes, this random value is simply 0 .

C++ Array with empty members

How to insert and print array elements?

Example 1: displaying array elements.

Here, we have used a for loop to iterate from i = 0 to i = 4 . In each iteration, we have printed numbers[i] .

We again used a range-based for loop to print out the elements of the array. To learn more about this loop, check C++ Ranged for Loop .

Note: In our range-based loop, we have used the code const int &n instead of int n as the range declaration. However, the const int &n is more preferred because:

Example 2: Take Inputs from User and Store Them in an Array

Once again, we have used a for loop to iterate from i = 0 to i = 4 . In each iteration, we took an input from the user and stored it in numbers[i] .

Then, we used another for loop to print all the array elements.

Example 3: Display Sum and Average of Array Elements Using for Loop

In this program:

Note: We used a ranged for loop instead of a normal for loop.

A normal for loop requires us to specify the number of iterations, which is given by the size of the array.

But a ranged for loop does not require such specifications.

If we declare an array of size 10 , then the array will contain elements from index 0 to 9 .

However, if we try to access the element at index 10 or more than 10 , it will result in Undefined Behaviour.

Table of Contents

Sorry about that.

Related Tutorials

C++ Tutorial

Passing Array to a Function in C++ Programming

Try PRO for FREE

IMAGES

  1. maximum number in an array with position in c

    array assignment in c

  2. How would i write a pseudocode for a parallel array array 1 contains 5 board lengths array 2

    array assignment in c

  3. Array assignment and reference in Java

    array assignment in c

  4. C# Array Operations Assignment Help By Online Tutoring Sessions

    array assignment in c

  5. AP Chapter 13 Lab 1 ArrayLists and Arrays Pts: 10 Name

    array assignment in c

  6. Solved: Assignment 06

    array assignment in c

VIDEO

  1. Get IGNOU Books & Solved Assignment for your exam from Gullybaba.com Get up-to 40% off on all books

  2. VBA & Excel Lesson 3: Arrays Picking Up Ranges from Excel

  3. Arrays in C# with examples

  4. Array C++

  5. JAVASCRIPT ASSIGNMENT

  6. ALDI Assignment C: Group 1

COMMENTS

  1. C Arrays (With Examples) - Programiz

    Arrays in C An array is a variable that can store multiple values. For example, if you want to store 100 integers, you can create an array for it. int data [100]; How to declare an array? dataType arrayName [arraySize]; For example, float mark [5]; Here, we declared an array, mark, of floating-point type. And its size is 5.

  2. C array declaration and assignment? - Stack Overflow

    You can do array assignment within structs: struct data { int arr [10]; }; struct data x = {/* blah */}; struct data y; y = x; But you can't do it directly with arrays. Use memcpy. Share Follow edited Nov 13, 2017 at 0:31 Jakob 343 5 15 answered Apr 13, 2009 at 16:50 user82238

  3. Arrays in C/C++ - GeeksforGeeks

    An array in C/C++ or be it in any programming language is a collection of similar data items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They can be used to store the collection of primitive data types such as int, float, double, char, etc of any particular type.

  4. C - Arrays - tutorialspoint.com

    To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows − type arrayName [ arraySize ]; This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type.

  5. Arrays - C# Programming Guide | Microsoft Learn

    You declare an array by specifying the type of its elements. If you want the array to store elements of any type, you can specify object as its type. In the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object. C# type [] arrayName; Example

  6. Array in C Programming: Here's How to Declare and Initialize ...

    Array in C can be defined as a method of clubbing multiple entities of similar type into a larger group. These entities or elements can be of int, float, char, or double data type or can be of user-defined data types too like structures. However, in order to be stored together in a single array, all the elements should be of the same data type .

  7. Array of Strings in C - GeeksforGeeks

    In C programming String is a 1-D array of characters and is defined as an array of characters. But an array of strings in C is a two-dimensional array of character types. Each String is terminated with a null character (\0). It is an application of a 2d array.

  8. C++ Arrays (With Examples) - Programiz

    In C++, each element in an array is associated with a number. The number is known as an array index. We can access elements of an array by using those indices. // syntax to access array elements array[index]; Consider the array x we have seen above. Elements of an array in C++ Few Things to Remember: The array indices start with 0.