Home > Software engineering >  get value from array pointer to pointer of a struct
get value from array pointer to pointer of a struct

Time:11-30

Im expecting to get the value of the pointer that pp is pointing to

this is my struct

struct game
{
    int rank;
    int year;
    char *name;
    char *platform;
    char *genre;
    char *publisher;

    // sales below represented in millions
    float NA_sales;
    float EU_sales;
    float JP_sales;
    float other_sales;
    float global_sales;
} Game;

i got the array of pointer to pointer as

struct Game **arr[MAX_NUM]; // max num is 100

and i assign

arr[counter] = &new_game; // new_game is calloc as struct game *new_game = calloc(1, sizeof(struct game));

i tried with

arr[counter]->publisher

but it return as

'*arr[counter]' is a pointer; did you mean to use '->'?
         printf("%s", arr[counter]->new_game->publisher);

CodePudding user response:

I do not know why you want to have so many levels of indirection.

To access using pointer

typedef struct game
{
    int rank;
    int year;
    char *name;
    char *platform;
    char *genre;
    char *publisher;

    // sales below represented in millions
    float NA_sales;
    float EU_sales;
    float JP_sales;
    float other_sales;
    float global_sales;
} Game;

/* ..... */
/* how to access */

    Game **arr[100];
    
    Game *newGame = calloc(1, sizeof(*newGame));
    arr[0] = &newGame;
    
    printf("%f", arr[0][0] -> NA_sales);
    printf("%f", (*arr[0]) -> NA_sales);
    printf("%f", (**arr) -> NA_sales);

CodePudding user response:

So the error here is that you have an extra level of indirection that the compiler isn't expecting which gives you an error with a bad suggestion. Since you have a pointer to pointer to array, the type of arr[counter] is still a pointer to pointer to struct. Here is how you access struct member via a pointer (as you know):

struct Foo* bar;
bar->a = 0;

But if that was a pointer to pointer, we need to dereference the first pointer to be able to use -> correctly:

struct Foo** bar;
(*bar)->a = 0;

Another way to look at it is bar->a is nothing more than syntax sugar for (*bar).a. You have an extra level of indirection, so without the ->, you would need (**bar).a.

  • Related