加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:52:40 所属栏目:百科 来源:网络整理
导读:说到C语言结构体数组的同时赋值,许多人一想就会想到用以下的这种方法,咱们来写一个例子: #include struct student { int a; int b ; int c ; }; struct student array1[1000] ; int main(void) { int i ; for(i = 0 ; i { array[i].a = 1 ; array[i].b = 2

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

#include

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,array[i].c);

}

return 0 ;

}

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

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

#include

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",array[i].c);

}

return 0 ;

}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对编程之家的支持。如果你想了解更多相关内容请查看下面相关链接

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读