gpt4 book ai didi

c - 如何返回指向结构数组内元素的指针?

转载 作者:太空宇宙 更新时间:2023-11-04 00:55:53 24 4
gpt4 key购买 nike

我在这里做错了什么?

/*
* 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 个 child (因为你访问 root->child[3]),所以你必须分配足够的内存:

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

此外,您应该返回 foobar 指针本身,而不是指向它的指针(即 return ptr; 而不是 return &ptr;

关于c - 如何返回指向结构数组内元素的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3510603/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com