【问题标题】:Initialize an array inside of a struct (w/ and array of values)初始化结构内的数组(w/和值数组)
【发布时间】:2019-07-06 20:34:23
【问题描述】:

是否可以在 C 中使用结构内部的值初始化数组?

#include <stdio.h>

struct student{
    int student_number[2];
    };

int main(void){

    struct student {
        int student_number = {35434, 56343};
    }

    struct student example_student;

    printf("%i \n", example_student.student_number[0]);


    return 0;
} 

编辑: 谢谢,Eric P,这消除了我对遇到的其他示例的一些困惑。

编辑上述代码以显示修复:

struct student{
    int student_number[2];
};

int main(void){

    struct student example_student = {
        .student_number = {35434, 56343}
    };

    printf("%i \n", example_student.student_number[0]);

【问题讨论】:

  • 您的编译器对此有何看法?
  • @EOF:他们的编译器说这种方式无效,但它没有回答是否可能使用其他语法的问题。
  • 我知道这不是一个正常运行的代码示例。这更多是为了解释这个问题。 error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token int student_number = {35434, 56343};

标签: c arrays structure


【解决方案1】:

您可以在定义结构对象时对其进行初始化,其中包括初始化结构内的数组成员:

struct student example_student = { { 35434, 56343 } };

你也可以具体标识你要初始化的结构成员:

struct student example_student = { .student_number = { 35434, 56343 } };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 2014-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多