[英]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.