【问题标题】:Why can't I get the correct value of structure pointer?为什么我不能得到结构指针的正确值?
【发布时间】:2019-11-18 11:06:14
【问题描述】:

我想在函数中使用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】:

    在这个函数中

    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 );
    

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

    或者由于数组的元素没有改变,那么参数应该有限定符const

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

    【讨论】:

      【解决方案2】:

      试试这个:

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

      【讨论】:

        【解决方案3】:
        struct cache_read_block
        {
            unsigned short ReadLength;    // How many words
        };
        typedef struct cache_read_block CACHE_READ_BLOCK;
        
        void getValue(CACHE_READ_BLOCK *ptr)
        {
            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;
        }
        

        【讨论】:

        • 你的答案应该解释你改变了什么以及为什么 - 不鼓励只使用代码的答案
        猜你喜欢
        • 2021-03-17
        • 2022-01-11
        • 1970-01-01
        • 1970-01-01
        • 2014-05-30
        • 2021-01-06
        • 2016-11-04
        • 1970-01-01
        • 2022-11-22
        相关资源
        最近更新 更多