Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

c pointer to array of structs

I know this question has been asked a lot, but I'm still unclear how to access the structs.

I want to make a global pointer to an array of structs:

typdef struct test
{
    int obj1;
    int obj2;
} test_t;

extern test_t array_t1[1024];
extern test_t array_t2[1024];
extern test_t array_t3[1025];

extern test_t *test_array_ptr;

int main(void)
{
    test_array_ptr = array_t1;

    test_t new_struct = {0, 0};
    (*test_array_ptr)[0] = new_struct;
}

But it gives me warnings. How should I access the specific structs with []?

Similarly, how should I create an array of pointers of struct type? test_t *_array_ptr[2];?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The syntax you are looking for is somewhat cumbersome, but it looks like this:

// Declare test_array_ptr as pointer to array of test_t
test_t (*test_array_ptr)[];

You can then use it like so:

test_array_ptr = &array_t1;
(*test_array_ptr)[0] = new_struct;

To make the syntax easier to understand, you can use a typedef:

// Declare test_array as typedef of "array of test_t"
typedef test_t test_array[];
...
// Declare test_array_ptr as pointer to test_array
test_array *test_array_ptr = &array_t1;
(*test_array_ptr)[0] = new_struct;

The cdecl utility is useful for deciphering complex C declarations, especially when arrays and function pointers get involved.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...