簡體   English   中英

指向結構中指針的指針。 function中如何分配memory

[英]pointer to pointer in struct. How to allocate memory in function

我有這樣的結構

    struct abc{
      struct xyz **x;
    }

並在 main 中創建指向 abc 的指針

     struct abc *o=(struct abc *)malloc(sizeof (struct abc));

我將它傳遞給 function hello 想將o->x傳遞給 function hello(struct xyz * xyz_obj)

在 function hello我想用 malloc 調用分配元素所以我像這樣創建了 function

        void hello(struct xyz **xyz_obj)
           {
               *xyz_obj=(struct xyz *)malloc(sizeof(struct xyz));}
                

但問題是如何調用hello以便將一個元素添加到數組中。

我嘗試了這個 function 調用,如下所示分配 o->x 所以在主要我可以使用o->xyz+some_number但這些嘗試不起作用

         hello(o->xyz+1); // NOT WORKING
         hello(*o->xyz+1) //NOT working
         hello((o)->xyz+1) //NOT working
         etc.

我將如何在 hello 中分配 ox 並在 main 中使用它

請添加一些解釋和方法來完成這個

struct xyz { /*something here*/ };

struct abc {
    struct xyz **x;
}

void hello(struct xyz **xyz_obj)
{
    // allocate one object of type struct xyz
    *xyz_obj = malloc(sizeof(struct xyz));
}

int main()
{
    // allocate an object of type struct abc
    struct abc *o = malloc(struct abc);
    // allocate storage for N pointers to struct xyz
    o->x = malloc(sizeof(struct xyz*) * N);

    hello(o->x    ); // first
    hello(o->x + 1); // second
    hello(o->x + 2); // third
    //... N times possible

    // access of object (of type struct xyz) at index n
    // o->x[n]->/*some field id*/;

    return 0;
}

您不能在 function hello中分配o->x (您可以分配 memory,但不能將其分配給o->x )。 為此,您必須重構(這意味着hello的原型必須重新聲明,並隨之調用hello )。

void hello(struct xyz ***xyz_obj)
{
    if (*xyz_obj == NULL)
        *xyz_obj = malloc(sizeof(struct xyz**) * N);

    // allocate one object of type struct xyz
    **xyz_obj = malloc(sizeof(struct xyz));
}

int main()
{
    //... same as before, but now we do not allocate any storage for o->x
    o->x = NULL;

    hello(&o->x); //since o->x is NULL, hello will allocate storage for o->x
    // hello(&(o->x + n));
    
    return 0;
}

我覺得第二種方法丑得要命。 它有什么好處? 只是分配任何存儲,如果它之前沒有分配。

根據您在評論部分的問題:

struct xyz {
    char var;
};

struct abc {
    struct xyz **x;
};

int main() {

    // assume 'o' is initialized and 'o->x' is not NULL
    struct abc *o;

    // access 'var' of 'struct xyz' at position (index) 'n'
    o->x[n]->var = 'c';

    // or
    struct xyz *x = o->x[n];
    x->var = 'c';

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM