[英]How to get struct field having pointer to the struct?
我有两个结构:
struct first
{
int* array;
}
struct second
{
struct first* firsts;
} *SECOND;
假设在某个地方我可以通过索引从SECOND->firsts
中获取struct first
的地址。 我怎样才能得到这个结构的array
? 我试过了
SECOND->firsts[index]->array
但存在expression must have pointer-to-struct-or-union type
错误。
没有 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;
}
给你。
#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;
}
程序 output 是
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
请注意,因为指针SECOND
struct first f
又包含指向数组的指针,然后两个对象都指向指针array
指向的同一个 memory 。
数组索引运算符[]
具有隐式指针取消引用。 所以这个表达式:
SECOND->firsts[index]
具有类型struct first
,而不是struct first *
,这意味着您不能在其上使用->
运算符。 您需要改用成员选择器运算符.
:
SECOND->firsts[index].array
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.