Home > Software design >  C language how to call a member of multi-dimensional array in corresponding to a structure
C language how to call a member of multi-dimensional array in corresponding to a structure

Time:02-08

I have a problem with how to call a member of a structure. For example, there is a struct

typedef struct FAVORITE_TBL_S
{
    UI32_T apple;
    UI32_T banana;
    UI16_T puzzle;
    UI16_T car;
}FAVORITE_TBL_T;

And in the function, I have created a multi-dimensional array about this struct.

FUNCTION_NO_T
call_myFavoriteTbl(
    const UI32_T unit,
    const UI32_T value)
{
    FUNCTION_NO_T ret = FUNCTION_E_GOOD;
    UI8_T num_of_list = 4;
    UI32_T i = 0;
    FAVORITE_TBL_T *ptr_fav = NULL;
    
    ptr_fav = priviate_alloc(sizeof(FAVORITE_TBL_T ) * num_of_list );
    priviate_memset(ptr_fav, 0, sizeof(FAVORITE_TBL_T ) * num_of_list );

    /* In this function, if I want to use member in the multi-dim array */
    for (i = 0, i < value, i  )
    {
        if (BRAND_PINKLADY == ptr_fav[i]->apple)
        {
            printf("I love it!");
        }
        else
        {
            printf("I don't want to eat.");
        }

        if (BRAND_COSTAPICA == ptr_fav[i].banana)
        {
            printf("I love it!");
        }
        else
        {
            printf("I don't want to eat.");
        }
    }

    return ret;
}

So why ptr_fav[i]->apple is wrong and ptr_fav[i].banana is right?

CodePudding user response:

As ptr_fav is an array of FAVORITE_TBL_T values, ptr_fav[i] is a FAVORITE_TBL_T value. It is not a pointer to FAVORITE_TBL_T.

As such, the . notation is correct.

Now, because ptr_fav[i] is equivalent to *(ptr i), you might write: (ptr_fav i)->apple, though I'm not sure why you'd want to do that.

The -> operator is used to access a field on a pointer to a structure.

CodePudding user response:

ptr_fav[i] has already dereferenced it and now you have structure value not pointer. If you want to use -> you should try (ptr_fav i)->apple.

  •  Tags:  
  • Related