Question

I have a struct named clients, and i created this array of structs.

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

clients PrimaryClients[100];

I'm calling a function to insert the data into this arrays, but i wanna to increase the amount of possible values until it reaches the limit. Is this the correct way?

int *pointer = (clients *) malloc(sizeof(clients));
Was it helpful?

Solution

Here's one example:

#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;
}

Doubling the size of the buffer each time you need to extend it is a common strategy; this tends to minimize the number of calls to realloc. It can also lead to serious internal fragmentation; if you have 128 elements and you need to store just one more, you wind up allocating 256 elements overall. You can also extend by a fixed amount, such as

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

Note that you don't want to assign the result of realloc directly to your buffer; if it returns NULL due to an error, you'll lose your reference to the memory you've already allocated, leading to a memory leak. Also, you don't want to update your array size until you know the call has succeeded.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top