【发布时间】:2021-02-13 12:40:38
【问题描述】:
我想将malloc 创建的两个数组(*a 和*b)的指针存储在一个函数中。
比如&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 *'
我想知道消除警告的根本原因和解决方案,并最终消除我的结构程序中的错误。
【问题讨论】:
-
在几个地方你的间接级别比你需要的少一级