07-02-2005 09:49 PM
07-02-2005 11:05 PM - edited 07-02-2005 11:05 PM
If you want the size of an array to vary during the execution of the program it must be dynamically allocated using malloc() or calloc(). I put together a small example of this in which when the array is resized, the contents are persisted as possible. This example elides error handling (such as an allocation failing) etc. but it should get you started.
I should mention that a potentially easier solution may be to use Handles instead of managing the array yourself; doing this is not a portable solution but it is a nice alternative that would do most of this management for you.
#define MIN(a, b) ((a) < (b) ? (a) : (b))
// *pArray can be NULL, oldSize or newSize can be zero
// newSize == zero will free up the array
void ChangeArraySize(int **pArray, int oldSize, int newSize)
{
int *newArray;
// allocate the space for the new array unless the size is <= 0
if (newSize > 0)
newArray = malloc(newSize * sizeof(int));
else
newArray = NULL;
// if an array already exists
if (*pArray)
{
// copy elements if necessary
if (oldSize > 0 && newSize > 0)
memcpy (*pArray, newArray, MIN(oldSize, newSize) * sizeof(int));
// free up the old array
free(*pArray);
}
// drop the new array in
*pArray = newArray;
}
int main(void)
{
int *array = NULL, arraySize = 0, i ;
ChangeArraySize(&array, arraySize, 100); // initial array allocation
arraySize = 100; // keep track of the current size
for (i = 0; i < arraySize; ++i)
array[i] = i;
ChangeArraySize(&array, arraySize, 50); // elements 0-49 are maintained
arraySize = 50;
for (i = 0; i < arraySize; ++i) // prints 0..49
printf("%d\n", i);
ChangeArraySize(&array, arraySize, 0); // free up
return 0;
}
Message Edited by Alex D on 07-02-2005 11:06 PM
07-04-2005 02:34 AM
07-04-2005 11:52 AM
The way I wrote the example, not really; that's basically what I implemented. The main reason I did it the long way was in the original post 48105 said, "I need to change the array size whenever the user change the select area and then put this array into an array list." The "put this array into an array list" led me to think that maybe he would want a slightly customized version that would leave the old array around so I tried to provide something that could be made a bit more flexible.
You're entirely correct; realloc would do essentially what I provided.
07-05-2005 01:50 AM
The number of stars you received probably indicates you were correct in your assumption 🙂
Thanks for the explanation.
Kind regards,
Erwin Timmerman
07-05-2005 07:23 AM