2010-08-18 93 views
1

我在这里做错了什么?如何返回指向结构数组内的元素的指针?

/* 
* 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 */ 

回答

1

我错了..做了两件事情中的行以上代码:

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

应改为简单地return &root->child[ x ];,这将返回一个指向的root->child[ x ]的内存地址。

该行foobar **ptr = this->search(1);将变为foobar *ptr = this->search(1);,这将允许使用. char来访问结构属性; ->不能使用,会输出垃圾。正确的使用示例:(*ptr).description

非常感谢adamk

+0

你错了 - '(* ptr).description'与* ptr->描述完全一样。 – caf 2010-08-19 01:07:20

1

您正在返回您检索到的指针的地址。你应该返回指针本身。

1

您只有一个孩子的malloc内存,但尝试为最多4个孩子设置ID。

它应该是这样的:

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

根有4个孩子(在您访问根 - >子[3]),所以你必须分配足够的内存:

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

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

+0

我纠正了代码,现在我只返回“返回ptr”;内存仍然是垃圾。如何返回指向root-> child [x]的内存地址的有效指针,以便稍后在函数外使用它。 ideia将搜索id并返回包含该id的对象。 – Joao 2010-08-18 10:04:30

+0

您是否记得将'foobar ** ptr = this-> search(1);'改为'foobar * ptr = this-> search(1);'也是? – adamk 2010-08-18 10:32:40

+0

是的..也做到了。我对C非常陌生,但是如果一个函数返回一个指向root-> child [x]的内存地址的指针(root是全局级别的var),则内存地址将在函数内部或外部有效。正确吗? – Joao 2010-08-18 10:39:44

1

您正在从函数返回局部变量的地址(return &ptr;)。一旦search函数退出,该对象将被销毁。试图从函数外部使用这个内存位置会导致未定义的行为。

+0

我纠正了代码,现在我只返回“返回ptr”;内存仍然是垃圾。 如何返回指向root-> child [x]的内存地址的有效指针,以便稍后在函数外部使用它。 理念是做一个id的搜索并返回包含该id的对象。 – Joao 2010-08-18 10:04:10

相关问题