typedef结构体指针类型困惑及动态分配数组报错求助
问题与解答:C++ typedef指针类型与动态数组分配错误
问题背景
给定结构体及typedef代码:
struct Part /*A Part record*/ { int ID; float Price; int Quantity; }; typedef Part *Partptr; // Part record pointer type; The type Partptr becomes synonymous with Part * typedef Partptr* Index; // The type Index becomes synonymous with Partptr *
尝试用Index DBindex定义该结构体的动态分配数组,编写代码DBindex = new Index[];时出现报错:
a value of type "Index *" cannot be assigned to an entity of type "Index"
原以为Index是指针类型,不清楚问题出在哪里。
问题分析与解决
先把所有typedef的别名还原成原生C++类型,就能一目了然:
typedef Part *Partptr;→Partptr就是Part*,也就是指向Part结构体的指针typedef Partptr* Index;→Index就是Partptr*,也就是Part**——指向Part指针的二级指针
现在看代码的问题核心:
Index DBindex;实际上是定义了一个Part**类型的二级指针变量new Index[];这里的Index是Part**,所以这个操作会分配一个存储Part**元素的数组,返回的指针类型是Index*,也就是Part***——三级指针
把三级指针赋值给二级指针变量,类型完全不匹配,所以编译器报错。
正确写法
根据需求分两种情况:
如果要创建存储Part指针的动态数组(比如每个元素指向一个独立的Part对象):
// 先定义数组长度,比如10个元素 int arr_len = 10; DBindex = new Partptr[arr_len]; // 等价于 new Part*[arr_len];这里
new Partptr[arr_len]返回的是Partptr*,也就是Part**,刚好和Index(即Part**)类型匹配。如果要创建直接存储Part结构体的动态数组:
完全不需要用到Partptr和Index,直接写:int arr_len = 10; Part* DBindex = new Part[arr_len];
内容的提问来源于stack exchange,提问作者Hub_Batch
相关产品推荐
相关产品推荐

