繁体   English   中英

数组初始化

[英]Array initialization

根据建议我修改了代码,但是如何在结构中初始化单个元素?

#include<stdio.h>

typedef struct student
{
    int roll_id[10];
    int name_id[10];
} student;

int main()
{
    student p = { {0} };  // if i want to initialize single element ''FIX HERE, PLs'' 
    student *pptr=&p;
    pptr->roll_id[9]={0}; // here is the error pointed 

    printf (" %d\n", pptr->roll_id[7]);

    return 0;
}

{0}仅作为聚合(数组或struct )初始值设定项有效。

int roll_id[10] = {0}; /* OK */
roll_id[0] = 5; /* OK */

int roll_id[10] = 5; /* error */
roll_id[0] = {0}; /* error */

你似乎想要的是初始化类型struct student p 这是通过嵌套的初始化程序完成的。

student p = { {0} }; /* initialize the array inside the struct */

我可以在你的代码中看到两个错误

    #include<stdio.h>

    typedef struct student
    {
    int roll_id[10];

    } student;

    int main()
    {

    student p;
    student *pptr=&p;
    pptr->roll_id[10]={0}; // in this line it should be pptr->roll_id[9]=0;


    printf (" %d\n", pptr->roll_id[7]);


    return 0;
    }

因为数组的长度是10所以索引应该是9,你只能在数组的初始化时使用{0}。

使用如下单数组元素初始化:

 pptr->roll_id[x] = 8 ; // here x is the which element you want to initialize.

使用如下进行整个数组初始化:

student p[] = {{10, 20, 30}};//just example for size 3.
student *pptr = p;
for (i = 0 ; i < 3; i++)
    printf ("%d\n", pptr->roll_id[i]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM