简体   繁体   English

了解如何动态创建结构数组并访问其元素

[英]understanding how to dynamically create an array of structure and access its elements

I need to pass the address of a pointer to a structure to a function, which inturn will dynamically allocate the memory for an array of structures and fill in the values. 我需要将指向结构的指针的地址传递给函数,该函数将动态地为结构数组分配内存并填充值。

Now from my calling method, once i return from the func1, i should be able to iterate through the array of structure and display the value of the structure variables. 现在从我的调用方法,一旦我从func1返回,我应该能够遍历结构数组并显示结构变量的值。

Can someone explain how to pass the address of the pointer to the structure, also iterating through the array of structures created dynamically ? 有人可以解释如何将指针的地址传递给结构,也可以迭代通过动态创建的结构数组?

my sample code looks like this: 我的示例代码如下所示:

struct test {
    int a;
    int b;
};

void func1(int *n,struct test **testobj)

{
    n=5;
    *testobj = (struct test*) malloc(n*sizeof(struct test));
    for(i=0;i<n;i++)
    {
        (*testobj)[i].a=1;
        (*testobj)[i].b=2;
    }
}

int main()
{
    struct test testobj;int n;
    func1(&n,&testobj);
    for(i=0;i<n;i++)
    {
        printf("%d %d",(*testobj)[i].a,*testobj)[i].b);
    }
    free(testobj);
}

In main() define a pointer to a test structure: 在main()中定义一个指向test结构的指针:

struct test *testPtr;

To take the address of that pointer use the & address-of operator: 要获取该指针的地址,请使用& address-of运算符:

&testPtr;

This returns the address of the pointer and has type struct test ** 这将返回指针的地址,并具有类型struct test **

You can then pass this into your function func1 , which does the correct allocation (although casting malloc() is generally considered bad practice - Do I cast the result of malloc? ). 然后你可以将它传递给你的函数func1 ,它执行正确的分配(尽管cast malloc()通常被认为是不好的做法 - 我是否应该转换malloc() 的结果? )。 Other than that func1() looks good... the line... 除了那个func1()看起来不错......这条线......

*testobj = malloc(n*sizeof(struct test));

... is correct. ... 是正确的。 *testobj dereferences your double pointer that you got by doing &testPtr , and stores the address of the new memory in your pointer. *testobj取消引用您通过执行&testPtr获得的双指针,并将新内存的地址存储在指针中。 You are also correct when you dereference your double-pointer using (*testobj)[i] because [] has higher precedence than * you needed to (as you've correctly done) surround the dereference with brackets to make sure that happens before you take the index. 当你提领你的双指针使用你也是正确的(*testobj)[i]因为[]的优先级高于*您需要(如你做得正确)用方括号括提领,以确保您之前发生拿指数。

Thus, when func1() returns the pointer testPtr should now point to the array of n test structures you allocated and can be accessed using testPtr[i].a etc. 因此,当func1()返回指针时, testPtr现在应该指向您分配的n test结构的数组,并且可以使用testPtr[i].a等进行访问。

EDIT: Your for loop should become 编辑:你的for循环应该成为

for(i=0;i<n;i++)
    printf("%d %d", testobj[i].a, testobj[i].b);

Your original for loop should have given you compilation errors? 你原来的for循环应该给你编译错误? In the original code testobj is not a pointer, therefore dereferencing it should not be possible. 在原始代码中testobj不是指针,因此不应该取消引用它。

So the summary answer is in main() declare testobj as a pointer and then access the array elements as testobj[n] :) 所以总结答案在main()声明testobj作为指针 ,然后作为testobj[n] :)访问数组元素

EDIT: As eric has pointed out, remove n=5; 编辑:正如埃里克指出的那样,删除n=5; from func1() . 来自func1() I think you meant *n=5 perhaps as some kind of debugging step... You probably mean to use n as the input to the function to say how many objects you want in your structure array. 我认为你的意思是*n=5或者作为某种调试步骤...你可能意味着使用n作为函数的输入来说明你想要在结构数组中有多少个对象。 Either initialise n or perhaps re-define func1() to be 初始化n或者可能重新定义func1()

void func1(int n,struct test **testobj) // n is no longer a poitner, just a number

create your array of pointers to structures in declaration step itself and simply pass it to the function 在声明步骤本身中创建指向结构的指针数组,并将其简单地传递给函数

struct test *testobj[10];
func1(&n,testobj);

This passes the whole array of pointers to the function 这会将整个指针数组传递给函数

Your code appears pretty much ok to me. 您的代码对我来说非常好。 only edit that should make it fine is-- 只编辑应该让它好 - 是

in place of 代替

struct test testobj;

put the following code 把以下代码

struct test  *testobj;

and keep the remaining as it is..! 并保持剩余的原样..!

here's the working version of what's required, here the memory is allocated in the called function just as required 这是所需内容的工作版本,这里根据需要在被调用函数中分配内存

#include <stdlib.h>
#include <stdio.h>
struct tests {
    int a;
    int b;
};

void func1(int *n,struct tests **testobj)

{
    int i;
    *n=5;
    *testobj = (struct tests*) malloc((*n)*sizeof(struct tests));
    for(i=0;i<(*n);i++)
    {
        (*testobj)[i].a=1;
        (*testobj)[i].b=2;
    }
}

int main()
{
    int i;
    struct tests *testobj;int n;
    func1(&n,&testobj);
    for(i=0;i<(n);i++)
    {
        printf("%d %d",(testobj)[i].a,testobj[i].b);
    }
    free(testobj);
}

It isn't entirely clear which version you're asking for, but one of these should cover it: 您要求的版本并不完全清楚,但其中一个应该涵盖它:

/* allocate some number of tests.
 *
 * out_n: out parameter with array count
 * returns: an array of tests
 */
struct test* allocate_some_tests(int *out_n) {
    int n = 5; /* hardcoded, random or otherwise unknown to caller */
    *out_n = n
    struct test *t = malloc(n * sizeof(*t));
    while (n--) {
        t[n].a = 1;
        t[n].b = 2;
    }
    return t;
}

/* allocate a specific number of tests.
 *
 * n: in parameter with desired array count
 * returns: an array of tests
 */
struct test* allocate_n_tests(int n) {
    struct test *t = malloc(n * sizeof(*t));
    while (n--) {
        t[n].a = 1;
        t[n].b = 2;
    }
    return t;
}

Note that you can just return the allocated array, you don't need a pointer-to-pointer here. 请注意,您只需返回已分配的数组,此处不需要指向指针的指针。

As for calling them, and iterating over the result: 至于调用它们,并迭代结果:

void print_tests(struct test *t, int n) {
    for (; n--; t++)
        printf("{%d, %d}\n", t->a, t->b);
}

int main()
{
    int count1; /* I don't know how many yet */
    struct test *array1 = allocate_some_tests(&count1);
    print_tests(array1, count1);

    int count2 = 3; /* I choose the number */
    struct test *array2 = allocate_n_tests(count2);
    print_tests(array2, count2);
}

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

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