error: expected expression when initialising a two dimensional structure variable in C

error: expected expression when initialising a two dimensional structure variable in C

所以我正在尝试了解 C 中的结构,并尝试在结构中使用二维字符数组。当我尝试在 main 中初始化它时,我收到一条错误消息“错误:预期表达式”。

struct students
{
    char roll_no[9][2];
}st;
int main()
{
    st.roll_no={"21BCD7001","21BCD7002"}; //this is where I get the error
}

当我尝试编译它时,我在 main() 中的第一个“{”出现错误。那么我该如何消除这个错误?

char roll_no[9][2]; 意思是“给我 9 个数组,每个 2 个字符长”。但是您实际上需要 2 个数组,每个数组长 10 个字符。 9 个字节用于数据,1 个字节用于空终止符。即:

char roll_no [2][10];

此外,st.roll_no={"21BCD7001","21BCD7002"};是赋值而不是初始化。你不能在 C 中分配数组,在这种情况下你必须使用 strcpy 。要实际初始化结构,您必须这样做:

struct students
{
    char roll_no[2][10];
};

int main()
{
  struct students st = {"21BCD7001","21BCD7002"}; 
}

或者您可以使用功能相同但更漂亮的样式:

struct students st = 
{ 
  .roll_no = {"21BCD7001","21BCD7002"} 
};