c指向结构数组的指针 [英] c pointer to array of structs

查看:40
本文介绍了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指向结构数组的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆