gpt4 book ai didi

c - 为结构动态分配内存的正确方法是什么?

转载 作者:可可西里 更新时间:2023-11-01 11:54:42 25 4
gpt4 key购买 nike

我正在开发一个程序,它应该在注册表中搜索特定值,并将它们及其路径存储在一个数组中。所以我不知道程序会找到多少键,因此我需要使用动态增长的数组。我现在正在使用这段代码,但我不确定它是否正确。

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

有人可以告诉我这是否可以吗?如果不是,我应该如何正确操作?

谢谢!

最佳答案

您已经掌握了要点。但是,您应该进行一些改进:

  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. 始终检查mallocrealloccalloc等的返回值:

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

    ...成为...

    RegArray[ ArrayCount ] = malloc( sizeof( struct data ) );
    if (RegArray[ ArrayCount ] == NULL) {
    /* handle error case */
    }
  4. 使用sizeof时使用变量而不是类型。我通常也会去掉 sizeof 中表达式周围无用的括号以提高可读性:

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

    ...成为...

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

关于c - 为结构动态分配内存的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20272842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com