我在這裏做錯了什麼?如何返回指向結構數組內的元素的指針?
/*
* 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 */
你錯了 - '(* ptr).description'與* ptr->描述完全一樣。 – caf 2010-08-19 01:07:20