2009-10-01 2 views
0

이 같은 구조체가 : 나는 (이전에 할당 된) 아이를 삭제하려면,간단한 중첩 된 포인터 질문

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; 
} 

지금 - 가정 :

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

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

내가 API를 다음과 같이 정의를 인덱스가 범위를 벗어되지 않습니다 :

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 ? 


} 

답변

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; 
} 
+0

감사합니다. 원래의 코드보다 훨씬 깔끔합니다. (필자는 확신했지만, ptrs 배열과 struct 배열을 혼합했기 때문에 혼란스러워졌습니다.) 대답 한 모든 사람들에게 감사드립니다. 감사합니다 – scoobydoo

2

이 NULL로 부모 -> 아이 [인덱스] 설정에 문제가 없습니다. 포인터 자체가 저장된 메모리가 아닌 포인터가 가리키는 메모리 만 해제했습니다.

2

물론이 작업을 수행 할 수 있습니다. 포인터는 값이 주소 인 변수입니다. 무료로 호출 한 후 포인터를 0 (또는 NULL)로 설정하는 것이 좋습니다. 따라서 null이 아니며 segfault를 피할 수 있습니다. 결론 : 귀하의 코드는 괜찮습니다.