繁体   English   中英

c指向结构数组的指针

[英]c pointer to 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;
}

但它给了我警告。 我应该如何使用[]访问特定的结构?

同样,我应该如何创建struct类型的指针数组? test_t *_array_ptr[2];

您正在寻找的语法有点麻烦,但它看起来像这样:

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

然后您可以像这样使用它:

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

要使语法更容易理解,可以使用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声明非常有用,尤其是在涉及数组和函数指针时。

test_t * test_array_ptr是指向test_t的指针。 它可以是指向test_t单个实例的test_t ,但它可以是指向test_t实例数组的第一个元素的指针:

test_t array1[1024];

test_t *myArray;
myArray= &array1[0];

这使myArray指向array1的第一个元素,指针算法允许您将此指针视为数组。 现在你可以像这样访问array1第二个元素: myArray[1] ,它等于*(myArray + 1)

但根据我的理解,你真正想要做的是声明指向test_t的指针,该指针将代表一个指向数组的指针数组:

test_t array1[1024];
test_t array2[1024];
test_t array3[1025];

test_t **arrayPtr;
arrayPtr = malloc(3 * sizeof(test_t*));   // array of 3 pointers
arrayPtr[0] = &array1[0];
arrayPtr[1] = &array2[0];
arrayPtr[2] = &array3[0];

你遇到的问题是你正在采取(*test_array_pointer)这是数组的第一个元素。 如果要分配给数组的特定元素,则可以执行以下操作...

function foo()
{
    test_array_ptr = array_t1;

    test_t new_struct = {0,0};
    memcpy( &test_array_ptr[0], &new_struct, sizeof( struct test_t ) );
}

如果你想总是分配给数组的第一个元素你可以这样做...

function foo()
{
    test_array_ptr = array_t1;

    test_t new_struct = {0,0};
    memcpy( test_array_ptr, &new_struct, sizeof( struct test_t ) );
}

其他人已经向我指出了,而且我真的完全忘记了因为没有在永远的好处使用它,你可以在C中直接分配简单的结构......

function foo()
{
    test_array_ptr = array_t1;

    test_t new_struct = {0,0};
    test_array_ptr[0] = new_struct;
}

我会使用指向指针的指针:

test_t array_t1[1024];
test_t **ptr;
ptr = array_t1;
ptr[0] = ...;
ptr[1] = ...;
etc.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM