如何在C++中初始化结构数组并用指针访问每个元素

How to initialize Array of Structure and Access each element with Pointer in C++

本文关键字:指针 访问 元素 数组 C++ 结构 初始化      更新时间:2023-10-16

在下面的程序中,我遇到了结构初始化问题。初始化后,我需要使用Pointer对每个结构元素进行定制。

#include <iostream>
using namespace std;
struct student{
int rollno;
float marks;
char name[45];
}*ptr;
int main(){
    //Getting initialization error
student s1[2]={1,50.23,"abc",2,65.54,"def"};
    for(int i=0;i<2;i++){
            //Need to cout using pointers
    cout<<s1[i].rollno<<s1[i].marks<<s1[i].name;
}
return 0;
}

您应该在{}:中包装数组的每个成员

student s1[2]={{1,50.23,"abc"},{2,65.54,"def"}};