• Home
  • 5.8 Array Assignment Restrictions

5.8 Array Assignment Restrictions

View Categories

5.8 Array Assignment Restrictions

In C, arrays are not modifiable lvalues, so an entire array cannot be assigned to another array using the assignment operator =. Individual elements can be assigned, but copying an array requires an element-wise or memory-copy operation.

#include <stdio.h>

int main(void)
{
    int first[3] = {10, 20, 30};
    int second[3] = {0};

    /* Copy elements individually */
    for (int i = 0; i < 3; i++)
    {
        second[i] = first[i];
    }

    second[0] = 99;

    printf("First array: ");

    for (int i = 0; i < 3; i++)
    {
        printf("%d ", first[i]);
    }

    printf("\nSecond array: ");

    for (int i = 0; i < 3; i++)
    {
        printf("%d ", second[i]);
    }

    printf("\n");

    return 0;
}

Example Output #

First array: 10 20 30
Second array: 99 20 30

Explanation #

The following declaration initializes second with three zero-valued elements:

int second[3] = {0};

Individual elements can be assigned normally:

second[0] = 99;

However, assigning one complete array to another is invalid:

second = first;  /* Invalid in C */

Array names also cannot be used as assignment targets:

first = second;  /* Invalid in C */

Valid and Invalid Operations #

Operation Valid? Reason
first[0] = 10; Yes Assigns an individual element
second[1] = first[1]; Yes Copies one element
second = first; No Arrays cannot be assigned as whole objects
first = second; No An array name is not a modifiable lvalue
int copy[3] = {1, 2, 3}; Yes Initializes an array at declaration

An array can be initialized when it is declared, but the same initializer syntax cannot be used later as an assignment.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *