How to Reassign Values to an Array in C Language

How to Reassign Values to an Array in C LanguageIt is not possible to directly assign values to an array name.In C language, when we declare and define (after initialization) an array, if we want to reassign values directly to the array, the C compiler may prompt:assignment to expression with array type.For example, the following code:

#include <stdio.h>
int main(){    int a[] = {1,2};    a = {2,1};     return 0;}

Why is this the case?This is because the variable a is just the name of the array, which is a pointer to the memory address of the first index of the array, and it is a constant that cannot be modified arbitrarily.So how can we reassign values to an already initialized array in C language?In the section titled Why Can’t We Directly Assign Values to String Type Members of Structures in C Language, we introduced a method for “reassigning values” to character arrays, which is through the strcpy() function in the string.h header file. However, if it is not a character array, such as an int or float type array, can we also use strcpy() to assign values to the entire array? For example, the following code:

#include <stdio.h>
#include <string.h>
int main(){    int a[] = {1,2};    strcpy(a,{2,1});     return 0;}

Clearly, this does not work. So how should we design the program?We can use the memcpy() method from the string.h header file. The example code is as follows:

#include <stdio.h>
#include <string.h>
int main(){    float a[] = {1.1f,2.2f};    float b[] = {2.2f,1.1f};    memcpy(a,b,sizeof(a));    for(int i=0;i<sizeof(a)/sizeof(a[0]);i++){        printf("%.1f ",a[i]);    }     return 0;}

The code compiles and runs, producing the output:

2.2 1.1

Of course, if you don’t mind the hassle, you can also design a loop to assign values index by index, as shown in the following code:

#include <stdio.h>
int main(){    float a[] = {1.1f,2.2f};    for(int i=0; i<sizeof(a)/sizeof(a[0]);i++){        a[i] = a[i] + 0.1f;    }    for(int i=0;i<sizeof(a)/sizeof(a[0]);i++){        printf("%.1f ",a[i]);    }     return 0;}

The code compiles and runs, producing the output:

1.2 2.3 

Disclaimer: The content is for reference only and does not guarantee accuracy!

Leave a Comment