Alfonso Morra wrote:
Hi,
I want to create a container structure (array/list etc), that is expandable.
Currently, I have static arrays like this
SomeStruct *ptrArray[MAX_NUM_STRUCT] ;
What I want to do is to be able to use ptrs to ptrs like so:
SomeStruct **ptrArray ;
However, I am unsure as to how to do the ff after the declaration above:
1). Allocate memory (both initially and for subsequent data structure
increases)
2). Navigate the array - i.e. index to specific element in the array
mtia
Use realloc() to create and extend a dynamic buffer. You can access
individual elements as you would with a normal array. Here's an
untested example:
#include <stdlib.h>
typedef struct {...} SomeStruct;
SomeStruct **extendArray(SomeStruct **arr, size_t *cursize, size_t
extent)
{
SomeStruct **tmp;
/**
* realloc() will return NULL on failure, address of the
* first element in the buffer on success. In order to
* extend the buffer, realloc() may move it to a
* different location, so the base address may change.
*/
tmp = realloc(arr, sizeof arr[0] * (*cursize + extent));
if (tmp)
{
arr = tmp;
*cursize += extent;
}
return arr;
}
int main(void)
{
/**
* Make sure array pointer is initially NULL
*/
SomeStruct **myArr = NULL;
size_ t arrSize = 0;
size_t i;
/**
* Initially allocate 20 elements to myArr
*/
myArr = extendArray(myArr, &arrSize, 20);
if (arrSize != 20)
{
/**
* Allocation failed; fatal error
*/
return EXIT_FAILURE;
}
for (i = 0; i < arrSize; i++)
{
/**
* do something with myArr[i]
*/
}
/**
* Extend array by another 5 elements
*/
myArr = extendArray(myArr, &arrSize, 5);
if (arrSize != 25)
{
/**
* Attempt to extend existing array failed.
*/
return EXIT_FAILURE;
}
for (i = 20; i < arrSize; i++)
{
/**
* do something with myArr[i]
*/
}
return EXIT_SUCCESS;
}
There are probably a hundred better ways to indicate success or
failure, and you'll want to add some intelligent error handling, but
that should give you the basic idea.