簡體   English   中英

如何返回指向結構數組中元素的指針?

[英]How can I return a pointer to an element inside an array of structs?

我在這里做錯了什么?

/*
 * Consider the following pseudo code !
 */
typedef struct foobar {
    unsigned char id, count;
    struct foobar *child;
} foobar;

foobar root = (foobar *) malloc( sizeof(struct foobar) );
root->child = (foobar *) malloc( sizeof(struct foobar) );

root->count++;
root->child[0].id = 1;

root->count++;
root->child[1].id = 2;

root->count++;
root->child[3].id = 3;

root->child[0].child = (foobar *) malloc( sizeof(struct foobar) );

root->child[0].child[0].count++;
root->child[0].child[0].id = 4;

root->child[1].child = (foobar *) malloc( sizeof(struct foobar) );
root->child[0].child[0].count++;
root->child[1].child[0].id = 5;

root->child[0].child[0].count++;
root->child[1].child[1].id = 6;

/* and so on */

/*
 * Function to search for an ID inside the tree,
 * it should call itself in order to go deeper into
 * the childs, but taht's not implemented here
 */
foobar *search( unsigned char id, foobar *start_node = NULL );
foobar *search( unsigned char id, foobar *start_node ) {
    if( start_node == NULL ) {
        unsigned char x;
        for( x = 0; x < root->count; x++ ) {
            if( root->child[ x ].id == id ) {
                foobar *ptr = &root->child[ x ];
                /* If I call ptr->id now, it will return the correct value */
                return &ptr;
            }
        }

    } else { /* not implemented */ }
}

/* Search the array for and ID */
foobar **ptr = this->search( 1 );
/* If I call ptr->id now, it will return memory garbage */

root有4個子級(訪問root-> child [3]時),因此必須分配足夠的內存:

root->child = (foobar *) malloc( sizeof(struct foobar) * 4 ); //at least 4

另外,您應該返回foobar指針本身,而不是指向它的指針(即return ptr;而不是return &ptr;

您將返回檢索到的指針的地址。 您應該返回指針本身。

您僅為一個孩子分配內存,但是嘗試為最多4個孩子設置ID。

應該是這樣的:

root->child = (foobar *) malloc( sizeof(struct foobar) * 4 );

您正在從函數search return &ptr;局部變量的地址( return &ptr; )。 退出search功能后,該對象將被銷毀。 嘗試從函數外部使用此內存位置將導致未定義的行為。

我在兩行代碼的上面做錯了..

foobar *ptr = &root->child[ x ];
return &ptr;

應該簡單地更改為return &root->child[ x ]; ,這將返回一個指向root->child[ x ]的內存地址的指針。

foobar **ptr = this->search( 1 ); 將成為foobar *ptr = this->search( 1 ); ,這將允許使用來訪問struct屬性. 字符 ->無法使用,將輸出垃圾。 正確的用法示例: (*ptr).description

非常感謝adamk

暫無
暫無

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

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