简体   繁体   中英

How to get struct field having pointer to the struct?

I have two structs:

struct first
{
    int* array;
}

struct second
{
    struct first* firsts;
} *SECOND;

Let's say somewhere I can get the address of one of struct first from SECOND->firsts by its index. How could I get array of this struct? I've tried

SECOND->firsts[index]->array

but there is expression must have pointer-to-struct-or-union type error.

No malloc checks and no free - just to show the idea

struct first {
    int* array; };

struct second {
    struct first* firsts; } *SECOND;

#define NUMFIRSTS   50
#define ARRSIZE 50

int main() {
    SECOND = malloc(sizeof(*SECOND));
    SECOND -> firsts = malloc(NUMFIRSTS * sizeof(*SECOND -> firsts));
    for(int f = 0; f < NUMFIRSTS; f++)
    {
        SECOND -> firsts[f].array = malloc(ARRSIZE * sizeof(*SECOND -> firsts[f].array));
    }

    //access
    SECOND -> firsts[5].array[10] = 23; 
}

Here you are.

#include <stdio.h>
#include <stdlib.h>

struct first
{
    int* array;
};

struct second
{
    struct first* firsts;
} *SECOND;

int main(void) 
{
    size_t n = 10;

    struct first f = { NULL };

    SECOND = malloc( sizeof( *SECOND ) );

    SECOND->firsts = &f;

    SECOND->firsts->array = malloc( n * sizeof( int ) );

    for ( size_t i = 0; i < n; i++ )
    {
        SECOND->firsts->array[i] = ( int )i;
    }

    for ( size_t i = 0; i < n; i++ )
    {
        printf( "%d ", SECOND->firsts->array[i] );
    }

    putchar( '\n' );

    for ( size_t i = 0; i < n; i++ )
    {
        printf( "%d ", f.array[i] );
    }

    putchar( '\n' );

    // ...
    // free all allocated memory

    return 0;
}

the program output is

0 1 2 3 4 5 6 7 8 9 
0 1 2 3 4 5 6 7 8 9 

Pay attention to that as the pointer SECOND contains pointer to struct first f that in turn contains pointer to array then the both objects points to the same memory pointed to by the pointer array .

The array index operator [] has an implicit pointer dereference. So this expression:

SECOND->firsts[index]

Has type struct first , not struct first * , which means you can't use the -> operator on it. You need to instead use the member selector operator . :

SECOND->firsts[index].array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM