c - 数组初始化

标签 c arrays

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

#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 */

关于c - 数组初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14193371/

相关文章:

c - C中数组的最大大小是多少?

c - 为什么我不能更改数组的第二个元素?

c++ - 程序因数组声明而崩溃

php - 获取 mysql_fetch_array 中的下一行

javascript - 如何不区分大小写包含使用 lodash 进行搜索

转换为克

Python C API 不加载模块

c - 为什么在有全局指针的情况下 fork 进程不会相互影响?

在 Visual Studio 中将可变长度 c 字符串转换为 Fortran 字符串

C - 在函数中初始化全局数组