You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何无法指向数组中的数组?C++结构体数组报错咨询

问题分析与解决

先贴出你的代码:

struct page { 
   
   int a;
   int b;
};

page chp1p1 = { 1, 2 }; // chapter 1 page 1

page chp1[12] = {

   chp1p1

};

page chapters[14] = {
   
   chp1

};

int main(){

   page& currChp = chapters[0];
   page& currPart = currChp[0];

   printf("If we are here then no errors");
   return 0;

}

错误根源

你犯了两个核心的类型匹配错误:

  1. chapters的类型定义完全错配:你想要的是「存储数组的嵌套数组」,但实际定义的page chapters[14]是单个page结构体的一维数组,每个元素只能装一个page对象,根本容纳不了chp1这种长度为12的page数组,所以chapters[0] = chp1本身就属于类型不兼容的非法赋值。
  2. currChp的引用对象错误:chapters[0]是单个page结构体,你用page& currChp引用它后,currChp就是普通的结构体对象,不是数组。这时写currChp[0]相当于对结构体用数组下标,完全不符合C++语法,必然报错。

修正方案

根据你嵌套存储章节-页面的需求,有两种常用修正方式:

方式一:固定长度的二维数组

如果所有章节的页数固定(比如都是12页),直接定义二维数组:

struct page { 
   int a;
   int b;
};

page chp1p1 = { 1, 2 };
// 定义14个章节,每个章节12页的二维数组
page chapters[14][12] = {0};

int main(){
    // 给第0章第0页赋值
    chapters[0][0] = chp1p1;
    // 引用第0章(这是一个长度为12的page数组)
    page (&currChp)[12] = chapters[0];
    // 引用第0章的第0页
    page& currPart = currChp[0];

    printf("If we are here then no errors");
    return 0;
}

方式二:指针数组(支持可变章节长度)

如果不同章节的页数不固定,用指针数组存储每个章节的数组首地址:

struct page { 
   int a;
   int b;
};

page chp1p1 = { 1, 2 };
page chp1[12] = {chp1p1};
// chapters是存储page数组指针的数组,共14个元素
page* chapters[14] = {chp1};

int main(){
    // currChp指向第0章的数组首地址
    page* currChp = chapters[0];
    // 引用第0章的第0页
    page& currPart = currChp[0];

    printf("If we are here then no errors");
    return 0;
}

内容的提问来源于stack exchange,提问作者PoppySickleSticks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 05:07:03