An alternative use of simultaneous assignment of C language struct arrays

  • 2020-06-12 10:08:02
  • OfStack

When it comes to assigning values to arrays of C structures, many people think of the following method:


#include <stdio.h>
struct student
{
 int a; 
 int b ; 
 int c ; 
};
struct student array1[1000] ;
int main(void)
{
 int i ;
 for(i = 0 ; i < 1000 ; i++)
 {
 array[i].a = 1 ;
 array[i].b = 2 ;
 array[i].c = 3 ;
 }
 for(i = 0 ; i < 1000 ; i++)
 {
 printf("array[%d].a:%d array[%d].b:%d array[%d].c:%d \n" ,
 i, array[i].a ,i, array[i].b ,i, array[i].c);
 }
 return 0 ;
}

This allows you to assign values to arrays of structures at the same time.

When reading the Linux kernel source code, it turns out that there is an even lesser-known method of the C language, using "..." The form of, the form of the number of elements, is the same thing. This usage is also allowed on standard C, free of syntax errors, so let's see how it works:


#include <stdio.h>
struct student
{
 int a; 
 int b ; 
 int c ; 
};
// For the first 0 An array to the first 999 Multiple struct arrays are assigned simultaneously 1 The content of the sample  
struct student array[1000] = {
 [0 ... 999] = {
 .a = 1 ,
 .b = 2 ,
 .c = 3 ,
 }
};
int main(void)
{
 int i ; 
 // Output the assigned value  
 for(i = 0 ; i < 1000 ; i++)
 {
 printf("array[%d].a:%d array[%d].b:%d array[%d].c:%d \n" ,
 i, array[i].a ,i, array[i].b ,i, array[i].c);
 }
 return 0 ;
}

conclusion


Related articles: