我正在开发一个程序,它应该在注册表中搜索特定值,并将它们及其路径存储在一个数组中。所以我不知道程序会找到多少键,因此我需要使用动态增长的数组。我现在正在使用这段代码,但我不确定它是否正确。
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++;
有人可以告诉我这是否可以吗?如果不是,我应该如何正确操作?
谢谢!
最佳答案
您已经掌握了要点。但是,您应该进行一些改进:
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 );
关于c - 为结构动态分配内存的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20272842/