C语言结构体数组同时赋值的另类用法分享!

说到C语言结构体数组的同时赋值,许多人一想就会想到用以下的这种方法,咱们来写一个例子:

  #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 ;  }

这样就可以实现对结构体数组同时赋值了。

阅读Linux内核源代码的时候看到了,原来C语言还有一种更少人知道的方法,使用 “…” 的形式,这种形式是指第几个元素到第几个元素,都是一样的内容。这种用法在标准C上也是允许的,没有语法错误,我们来看看它是怎么用的:

  #include <stdio.h>  struct student  {   int a;    int b ;    int c ;   };  //对第0个数组到第999个结构体数组同时赋值一样的内容   struct student array[1000] = {   [0 ... 999] = {   .a = 1 ,   .b = 2 ,   .c = 3 ,   }  };  int main(void)  {   int i ;    //输出赋值后的数值    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 ;  }

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对<计算机技术网(www.ctvol.com)!!>的支持。如果你想了解更多相关内容请查看下面相关链接

—-想了解C语言结构体数组同时赋值的另类用法分享!全部内容且更多的C语言教程关注<计算机技术网(www.ctvol.com)!!>

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/482583.html

(0)
上一篇 2020年11月9日
下一篇 2020年11月9日

精彩推荐