繁体   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