2

Is it possible to initialize an array with values inside of a structure in 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;
} 

Edit: Thanks, Eric P, this cleared this up some of the confusion I was having with other examples I came across.

Edit of the above code to show fix:

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]);
3
  • What does your compiler say about it? Commented Jul 6, 2019 at 20:35
  • 1
    @EOF: Their compiler says that way is not valid, but it does not answer the question of whether it is possible, using some other syntax. Commented Jul 6, 2019 at 20:43
  • I'm aware that this is not a functioning code example. This was more an for explaining the question. error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token int student_number = {35434, 56343}; Commented Jul 6, 2019 at 20:51

1 Answer 1

4

You can initialize a structure object when you define it, and that includes initializing an array member inside the structure:

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

You can also specifically identify the structure member you want to initialize:

struct student example_student = { .student_number = { 35434, 56343 } };
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.