如何解决C数组,用于存储malloc数组的指针
我想将*a
创建的两个数组(*b
和malloc
)的指针存储在函数中。
例如,如果&a[0]=0x0061FEC8
和&b[0]=0x007700FE
,则存储这两个指针的数组应为c[0]=0x0061FEC8
和c[1]=0x007700FE
void storePointers(int **ptrArray){
// create two arrays a and b by malloc
int *a = (int *)malloc(5*sizeof(int)); // a stores 5 integers
int *b = (int *)malloc(10*sizeof(int)); // b stores 10 integers
// create an array to store the pointers of a and b
*ptrArray = (int **)malloc(2*sizeof(int*));
(*ptrArray)[0] = a;
(*ptrArray)[1] = b;
}
int main(){
int *mArray = NULL;
storePointers(&mArray);
// these two lines should print 0x0061FEC8 and 0x007700FE
printf("mArray[0]: %p\n",mArray[0]);
printf("mArray[1]: %p\n",mArray[1]);
return 0;
}
该程序实际上有效。但是编译器显示警告消息:
warning: assignment to 'int' from 'int *' makes integer from pointer without a cast [-Wint-conversion]
(*ptrArray)[0] = a;
warning: assignment to 'int' from 'int *' makes integer from pointer without a cast [-Wint-conversion]
(*ptrArray)[1] = b;
我假设int
很常见,所以编译器自己解决了问题,以便我的程序正常运行?我有另一个类似的程序,但是它使用struct
。因此,我得到的不是警告,而是警告
Error: incompatible types when assigning to type 'myStruct' from type 'myStruct *'
我想知道摆脱警告的根本原因和解决方案,并最终消除我的struct程序中的错误。
解决方法
如果数组为int *
,则数组为int **
;如果要返回,将数组作为out参数,则需要一个指针对此-int ***
。因此,您需要更改mArray
的类型以及ptrArray
参数:
void storePointers(int ***ptrArray){
// create two arrays a and b by malloc
int *a = (int *)malloc(5*sizeof(int)); // a stores 5 integers
int *b = (int *)malloc(10*sizeof(int)); // b stores 10 integers
// create an array to store the pointers of a and b
*ptrArray = (int **)malloc(2*sizeof(int*));
(*ptrArray)[0] = a;
(*ptrArray)[1] = b;
}
int main(){
int **mArray = NULL;
storePointers(&mArray);
// these two lines should print 0x0061FEC8 and 0x007700FE
printf("mArray[0]: %p\n",mArray[0]);
printf("mArray[1]: %p\n",mArray[1]);
return 0;
}
如果您将类型从int
更改为其他内容,那应该可以。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。