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));
1 Answer 1
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.
4 Comments
arr[i].name. The subscript operation implicitly dereferences arr; that is, if the type of arr is client *, then the type of arr[i] is client.*tmp = realloc(client, sizeof(*arr * ( arrSize + 1 ))); and i dont know what is the error...realloc call should be written as realloc(client, sizeof *arr * (arrSize + 1)); check your parentheses.
malloccall allocates space for oneclientstructure. You might also want to read aboutrealloc.malloc(), which is wrong. Apart from that, are you looking forrealloc()?realloc()to embiggenPrimaryClientsas it is not allocated withmalloc().pointerbe of typeint*that is a pointer tointand not a pointer toclients,clients*?