简单的嵌套指针问题

时间:2009-10-01 14:14:11

标签: c pointers

我的结构是这样的:

struct Child
{
  int foo;
  char bar[42];
};

struct Parent
{
   long foobar;
   struct Child ** children;
   size_t num_children;
}

我已经定义了这样的API:

struct Parent * ParentAlloc() { struct Parent* ptr = (struct Parent*)calloc(1, sizeof(struct Parent));
ptr->children = (struct Child**)calloc(SOME_NUMBER, sizeof(struct Child*));
return ptr;
}

现在,如果我想删除一个(先前分配的)子节点 - 假设索引不在界外:

void FreeChild(struct Parent* parent, const size_t index)
{
   free(parent->children[index]);

   //now I want to mark the address pointed to in the array of pointers as null, to mark it as available

   //I dont think I can do this (next line), since I have freed the pointer (its now "dangling")
   parent->children[index] = 0; // this is not right. How do I set this 'freed' address to null ?


}

3 个答案:

答案 0 :(得分:2)

将parent-> children [index]设置为NULL没有问题。 您只释放了指针指向的内存,而不是存储指针本身的内存。

答案 1 :(得分:2)

当然你可以这样做。指针是一个变量,其值是一个地址。在调用free之后将指针设置为0(或NULL)是完全可以的,实际上是好的做法,这样你就可以检查它们是否为非null并避免段错误。底线:你的代码没问题。

答案 2 :(得分:0)

您正在将指针数组与结构数组混合在一起。删除双星并操作偏移:


...
struct Parent
{
  long foobar;
  struct Child* kids;
  size_t numkids;
};
...
struct Parent * ParentAlloc()
{
  struct Parent* ptr = ( struct Parent* )calloc( 1, sizeof( struct Parent ));
  ptr->kids = ( struct Child* )calloc( SOME_NUMBER, sizeof( struct Child ));
  ptr->numkids = SOME_NUMBER; /* don't forget this! */
  return ptr;
}
...
struct Child* GetChild( struct Parent* p, size_t index )
{
  assert( p );
  assert( index < p->numkids );
  return p->kids + index;
}