0

我有一个名为 clients 的结构,我创建了这个结构数组。

typedef struct auxiliarRegistre{
 char name[50];
 char CPF[20];
 char addr[100];
}clients;

clients PrimaryClients[100];

我正在调用一个函数将数据插入到这个数组中,但我想增加可能值的数量,直到它达到限制。这是正确的方法吗?

int *pointer = (clients *) malloc(sizeof(clients));
4

1 回答 1

2

这是一个例子:

#include <stdlib.h>

typedef struct auxiliarRegistre { ... } clients;

int arrSize = SOME_START_SIZE;
clients *arr = malloc( arrSize * sizeof *arr );

/**
 * Do stuff with arr.  When you need to extend the buffer, do the following:
 */

clients *tmp = realloc( clients, sizeof *arr * ( arrSize * 2));
if ( tmp )
{
  arr = tmp;
  arrSize *= 2;
}

每次需要扩展缓冲区时都将缓冲区的大小加倍是一种常见的策略;这往往会最大限度地减少对realloc. 它还可能导致严重的内部碎片化;如果你有 128 个元素,而你只需要再存储一个,你最终会分配 256 个元素。您也可以按固定金额延期,例如

clients *tmp = realloc( clients, sizeof *arr * ( arrSize + extent ));
if ( tmp )
{
  arr = tmp;
  arrSize += extent;
}

请注意,您不想将结果realloc直接分配给缓冲区;如果由于错误而返回 NULL,您将丢失对已分配内存的引用,从而导致内存泄漏。此外,在您知道调用成功之前,您不希望更新数组大小。

于 2013-10-28T14:28:33.790 回答