2013-11-28 2 views
1

나는 특정 값을 찾기 위해 레지스트리를 검색하고, 그 값을 배열에 저장해야하는 프로그램을 만들고있다. 그래서 프로그램이 얼마나 많은 키를 찾을 지 알지 못한다. 따라서 나는 동적으로 성장하는 배열을 사용할 필요가있다. 지금 당장이 코드를 사용하지만 올바른지 확실하지 않습니다.구조체에 동적으로 메모리를 할당하는 올바른 방법은 무엇입니까?

struct data 
{ 
char * Path; 
char * Key; 
}; 
struct data **RegArray = NULL; 

int ArrayCount = 0; 

// .... 
// .... 

// search the registry here.... 

// value has been found, so i should add it to the array here 
RegArray = (struct data **)realloc(RegArray, (ArrayCount + 1) * sizeof(struct data *)); 
RegArray[ ArrayCount ] = (struct data *)malloc(sizeof(struct data)); 

RegArray[ ArrayCount ]->Path = _strdup(CurrentPath); 
RegArray[ ArrayCount ]->Key = _strdup(CurrentKey); 

ArrayCount++; 

이 사람이 나에게 좋을지 말 수 있는지 알려주시겠습니까? 그렇지 않다면 어떻게해야합니까?

감사합니다.

+0

을 나는 또한 일반적으로 가독성을 향상시키기 위해 sizeof의 표현 주위에 쓸모없는 괄호를 삭제 realloc은 할당되지 않은 데이터와 함께 사용할 수 없습니다. –

+1

@AlterMann :'NULL' 포인터의'realloc'은'malloc'과 같습니다. – netcoder

+0

netcoder, 맞습니다, 죄송합니다 –

답변

1

당신은 그 요점을 가지고 있습니다. 그러나, 몇 가지 개선 당신이해야이 있습니다 :

  1. Don't cast the return value of malloc, realloc, calloc, etc. :

    RegArray[ ArrayCount ] = (struct data *)malloc(sizeof(struct data)); 
    

    ...된다 ...

    RegArray[ ArrayCount ] = malloc(sizeof(struct data)); 
    
  2. 가 항상 realloc을 메모리 누수를 방지하기 위해 성공했는지를 확인한 후 의도 한 위치에 할당하기 전에 임시 변수 :

    RegArray = (struct data **)realloc(RegArray, (ArrayCount + 1) * sizeof(struct data *)); 
    

    ...는 ...

    ...
    struct data **tmp = realloc(RegArray, (ArrayCount + 1) * sizeof(struct data *)); 
    if (tmp == NULL) { 
        /* handle error case */ 
    } 
    RegArray = tmp; 
    
  3. 항상 malloc의 반환 값, realloc, calloc 등 :

    RegArray[ ArrayCount ] = (struct data *)malloc(sizeof(struct data)); 
    

    을 확인 ...하게된다

    RegArray[ ArrayCount ] = malloc(sizeof(struct data)); 
    if (RegArray[ ArrayCount ] == NULL) { 
        /* handle error case */ 
    } 
    
  4. e 변수를 사용하는 경우에는 sizeof을 사용하십시오.

    RegArray[ ArrayCount ] = malloc(sizeof **RegArray); 
    
1

...

RegArray[ ArrayCount ] = malloc(sizeof(struct data)); 

...된다 목록 방법 :

struct Data 
{ 
char * Path; 
char * Key; 
Data * next; 
}; 

void deallocate(Data *ptr){ 
    free(ptr->Path); 
    free(ptr->Key); 
    free(ptr); 
} 

Data *removeElement(Data *list, char *Key){ 
    Data *ptr = list; 
    Data *prev = NULL; 
    while(ptr != NULL){ 
     if(strcmp(Key,ptr->Key) == 0){ 
      if(prev != NULL){ 
       prev->next = ptr->next; 
       deallocate(ptr); 
      } 
      else{ 
       prev = ptr; 
       list = ptr->next; 
       deallocate(prev); 
      } 
     } 
     else{ 
      ptr = ptr->next; 
     } 
    } 
    return list; 
} 

Data * addElement(Data *list, char *path, char *key){ 
    if(list == NULL) { 
     list = (Data *)malloc(sizeof(Data)); 
     return list; 
    } 
    Data *cursor = list; 
    while(cursor != NULL){ 
     cursor = cursor->next; 
    } 
    cursor = (Data *)malloc(sizeof(Data)); 
    cursor->next = NULL; 
    cursor->path = path; 
    cursor->key = key; 
    return list; 
} 

int main(){ 
    Data *list = NULL; 

    // value has been found 
    list = addElement(list,path,key); 

return 0; 
} 
+0

답변 해 주셔서 대단히 감사합니다. 이것은 또한 매우 도움이되지만, 불행히도, 나는 오직 하나의 대답만을 받아 들일 수 있습니다. – kampi

+0

@ HAL9000, malloc에서 캐스트를 제거해야합니다. 자세한 내용은 다음을 참조하십시오. http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc –

+0

@ HAL9000 : 요소를 제거하는 코드를 게시 하시겠습니까? 고맙습니다. – kampi

관련 문제