c指向结构数组的指针

时间:2013-04-24 20:32:10

标签: c arrays pointers struct

我知道这个问题已被问到很多,但我仍然不清楚如何访问这些结构。

我想创建一个结构数组的全局指针:

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];

4 个答案:

答案 0 :(得分:16)

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

// 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声明非常有用,尤其是在涉及数组和函数指针时。

答案 1 :(得分:5)

test_t * test_array_ptr是指向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];

答案 2 :(得分: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;
}

答案 3 :(得分:0)

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

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