簡體   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