c指向结构数组的指针

c指向结构数组的指针

本文介绍了c指向结构数组的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题已经问了很多,但是我仍然不清楚如何访问这些结构.

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 []?

类似地,我应该如何创建结构类型的指针数组? test_t *_array_ptr[2];?

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

推荐答案

您正在寻找的语法有些繁琐,但看起来像这样:

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;

要使语法更易于理解,可以使用typedef:

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;

cdecl 实用程序对于解密复杂的C声明非常有用,尤其是在涉及数组和函数指针时.

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

这篇关于c指向结构数组的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 12:27