将指针传递给堆栈分配的数组以实现功能

时间:2013-04-21 20:19:42

标签: c function stack parameter-passing allocation

我有一个下面的原型函数,第三个参数(输出变量)是唯一相关的:

int ioman_write_pages(void**, unsigned, HDD_address**, /*rest is irrelevant*/)

HDD_address类型以防有人问:

typedef union { 
    unsigned long long address;

    struct {
      unsigned long long offset : 12;
      unsigned long long page_number : 26;
      unsigned long long : 0;
    } paddress;
} HDD_address;

使用堆分配调用方案(完美运行):

HDD_address* page = (HDD_address*)malloc( pagecount * sizeof(HDD_address) );
memset( page, 0, pagecount * sizeof(HDD_address) );

ioman_write_pages( data, 3, &page, block, NULL, NULL );

printf( "Pages written to: [%d, %d, %d]\n", 
        page[0].address >> 9, 
        page[1].address >> 9, 
        page[2].address >> 9 );

输出(预期:0,16,24):

Pages written to: [0, 16, 24]

上面的堆分配没有问题。

但是,如果我尝试堆叠分配“page”:

HDD_address page[pagecount];
memset( page, 0, pagecount * sizeof(HDD_address) );

ioman_write_pages( data, 3, &page, block, NULL, NULL );

输出,虽然数据明智无意义,但它是一致的:

Pages written to: [166956, 0, 0]

编译上述内容时编译警告:

note: expected ‘union HDD_address **’ but argument is of type ‘union HDD_address (*)[(sizetype)(pagecount)]’

堆叠分配,“修正”警告:

DD_address page[pagecount];
memset( page, 0, pagecount * sizeof(HDD_address) ); 
HDD_address* ppage = page; 

int r = ioman_write_pages( data, 3, &ppage, block, NULL, NULL );

输出,每次运行都是一致的,但是无意义:

Pages written to: [1610376, 2856870, 610607]

我根本无法理解这一点,有人请赐教!

1 个答案:

答案 0 :(得分:1)

如果你必须传递一个双指针,那么函数可能会自己进行分配(并改变指针指针)。