简体   繁体   English

如何获取具有指向结构的指针的结构字段?

[英]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.假设在某个地方我可以通过索引从SECOND->firsts中获取struct first的地址。 How could I get array of this struct?我怎样才能得到这个结构的array I've tried我试过了

SECOND->firsts[index]->array

but there is expression must have pointer-to-struct-or-union type error.但存在expression must have pointer-to-struct-or-union type错误。

No malloc checks and no free - just to show the idea没有 malloc 检查并且没有免费 - 只是为了展示这个想法

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程序 output 是

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 .请注意,因为指针SECOND struct first f又包含指向数组的指针,然后两个对象都指向指针array指向的同一个 memory 。

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.具有类型struct first ,而不是struct first * ,这意味着您不能在其上使用->运算符。 You need to instead use the member selector operator .您需要改用成员选择器运算符. :

SECOND->firsts[index].array

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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