【问题标题】:C array to store the pointers of malloc'd arrays用于存储 malloc 数组指针的 C 数组
【发布时间】: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 *'

我想知道消除警告的根本原因和解决方案,并最终消除我的结构程序中的错误。

【问题讨论】:

  • 在几个地方你的间接级别比你需要的少一级

标签: arrays c pointers malloc


【解决方案1】:

如果一个数组是int *,那么一个数组数组就是int **,如果你想返回一个数组数组作为输出参数,那么你需要一个指向它的指针—— 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 更改为其他类型,这应该会起作用。

【讨论】:

  • 另一种选择是使用函数的返回值来返回值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-16
  • 1970-01-01
  • 2021-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多