C语言struct的double指针sample_arr赋值与元素访问问题
问题解答
核心概念前置说明
sample_t **sample_arr 是双指针类型,含义是:该指针指向一组sample_t *(结构体指针)类型元素的首地址,也就是说它存储的是「结构体指针数组」的首地址,不能直接指向「结构体实体数组」的首地址。
问题1错误原因与解决方案
错误原因
你定义的table是sample_t [LEN]类型,属于结构体实体数组,数组名隐式转换后的指针类型是sample_t *,和sample_t **类型不匹配,因此报类型不兼容警告。
正确实现
你需要先构造一个sample_t *类型的指针数组,每个元素对应存储table数组中实体的地址,再将该指针数组的首地址赋值给sample_arr,即可匹配双指针类型:
int main() { new_sample_t new_sample; // 构造结构体指针数组,每个元素存table对应元素的地址 sample_t *sample_ptr_arr[LEN] = {&table[0], &table[1], &table[2], &table[3], &table[4]}; // 指针数组名隐式转首元素指针,类型是sample_t **,正好匹配 new_sample.sample_arr = sample_ptr_arr; print_new_sample_array(new_sample.sample_arr); return 0; }
问题2错误原因与解决方案
错误原因
你写的new_sample[i]是完全错误的:new_sample是new_sample_t类型的单个变量,不是数组,不能用下标访问。正确的访问层级是:
- 先取
new_sample的sample_arr成员(双指针,即结构体指针数组的首地址) - 用下标
[i]拿到数组中第i个sample_t *指针 - 用
->访问指针指向的结构体的属性
正确写法
for(int i = 0; i < LEN; i++){ printf("This is the elem in the array: %s", new_sample.sample_arr[i]->name); }
补充修正:原有打印函数的错误
你原来的print_new_sample_array中计算len的逻辑完全错误:table是sample_t类型的数组,除以new_sample_t的大小得到的长度毫无意义,直接用宏LEN即可:
void print_new_sample_array(sample_t **sample_arr) { for(int i = 0; i < LEN; i++){ printf("The array element is: %s\n", sample_arr[i]->name); } }
内容的提问来源于stack exchange,提问作者DavidKanes
相关产品推荐
相关产品推荐

