我正在开发一个程序,它应该在注册表中搜索特定的值,并将它们和它们的路径存储在一个数组中。所以我不知道程序会找到多少个密钥,因此我需要使用一个动态增长的数组。我现在使用这个代码,但我不确定它是否正确。
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 :(得分: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 ) );
为了防止内存泄漏,在检查是否成功后,在分配到目标位置之前,始终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;
始终检查malloc
,realloc
,calloc
等的返回值:
RegArray[ ArrayCount ] = ( struct data *)malloc( sizeof( struct data ) );
... ...变为
RegArray[ ArrayCount ] = malloc( sizeof( struct data ) );
if (RegArray[ ArrayCount ] == NULL) {
/* handle error case */
}
使用sizeof
时使用变量而不是类型。我通常也会在sizeof
中的表达式周围放下无用的括号以提高可读性:
RegArray[ ArrayCount ] = malloc( sizeof( struct data ) );
... ...变为
RegArray[ ArrayCount ] = malloc( sizeof **RegArray );
答案 1 :(得分:1)
列表方式:
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;
}