Reputation: 67
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]);
Upvotes: 2
Views: 57
Reputation: 224596
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 } };
Upvotes: 4