为什么不能获得正确的结构指针值?

问题描述 投票:0回答:1

我想在函数中使用ptr [1]-> ReadLength,但它始终显示0。

解决此问题的方法是什么?

谢谢。

struct cache_read_block
{
    unsigned short ReadLength;    // How many words
};
typedef struct cache_read_block CACHE_READ_BLOCK;

void getValue(CACHE_READ_BLOCK (*ptr)[100])
{
    printf("index %d\n", ptr[0]->ReadLength);
    printf("index %d\n", ptr[1]->ReadLength);
}

int main(void) {

CACHE_READ_BLOCK arr[100] = {0};

 arr[0].ReadLength = 10;
 arr[1].ReadLength = 5;

 getValue(&arr);

 system("pause");
 return 0;
}
c arrays pointers implicit-conversion dereference
1个回答
1
投票

在此功能中

void getValue(CACHE_READ_BLOCK (*ptr)[100])
{
    printf("index %d\n", ptr[0]->ReadLength);
    printf("index %d\n", ptr[1]->ReadLength);
}

参数是指向CACHE_READ_BLOCK类型的100个元素的数组的指针。您必须首先取消引用指针。

void getValue(CACHE_READ_BLOCK (*ptr)[100])
{
    printf("index %d\n", ( *ptr )[0].ReadLength);
    printf("index %d\n", ( *ptr )[1].ReadLength);
}

通过以下方式声明和定义函数会更简单

void getValue( CACHE_READ_BLOCK *ptr )
{
    printf("index %d\n", ptr[0].ReadLength);
    printf("index %d\n", ptr[1].ReadLength);
}

和这样称呼

getValue( arr );

用作函数参数的数组被隐式转换为指向其第一个元素的指针。

© www.soinside.com 2019 - 2024. All rights reserved.