将指针传递给动态数组
将指针传递给动态数组是否正确? 它会起作用吗? 如果没有,请解释为什么,如果确实如此,也解释原因。 谢谢。
struct record { char * community_name; double data[10]; double crimes_per_pop; }; void allocate_struct_array(struct record *** r); int main() { /* allocating pointer to an array of pointers */ struct record ** r; /* passing its address to a function */ allocate_struct_array( &(**r) ); } /* function gets an address */ void allocate_struct_array(struct record *** r) { ... }
我试图做的是分配一个指针数组,其中每个指针指向结构记录。 函数假设仅使用指向r的指针来分配此数组,该指针在main中声明。 正在玩这个代码,但无法使其工作。
在函数接口中,您只需要一个双指针struct record **r
而不是三指针。
数组可以用struct record *array
; 所以指向它的指针是struct record **ptr_to_array
。
用&array
调用该函数。
struct record { char * community_name; double data[10]; double crimes_per_pop; }; void allocate_struct_array(struct record **r); int main() { struct record *r; allocate_struct_array(&r); } void allocate_struct_array(struct record **r) { *r = malloc(23 * sizeof(struct record)); ... }
我不知道你要做什么,但至少你有程序错误。
allocate_struct_array( &(**r) );
需要是 –
allocate_struct_array(&r);