c dynamic array code example
Example 1: C dynamic array
typedef struct {
int *array;
size_t used;
size_t size;
} Array;
void initArray(Array *a, size_t initialSize) {
a->array = malloc(initialSize * sizeof(int));
a->used = 0;
a->size = initialSize;
}
void insertArray(Array *a, int element) {
// a->used is the number of used entries, because a->array[a->used++] updates a->used only *after* the array has been accessed.
// Therefore a->used can go up to a->size
if (a->used == a->size) {
a->size *= 2;
a->array = realloc(a->array, a->size * sizeof(int));
}
a->array[a->used++] = element;
}
void freeArray(Array *a) {
free(a->array);
a->array = NULL;
a->used = a->size = 0;
}
Example 2: allocate memory c
ptr = (castType*)calloc(n, size);
Example 3: C dynamic array
Array a;
int i;
initArray(&a, 5); // initially 5 elements
for (i = 0; i < 100; i++)
insertArray(&a, i); // automatically resizes as necessary
printf("%d\n", a.array[9]); // print 10th element
printf("%d\n", a.used); // print number of elements
freeArray(&a);
Example 4: c infiite array
int main(int argc, char *argv[])
{
int i;
double* p; // We uses this reference variable to access
// dynamically created array elements
p = calloc(10, sizeof(double) ); // Make double array of 10 elements
for ( i = 0; i < 10; i++ )
*(p + i) = i; // put value i in array element i
for ( i = 0; i < 10; i++ )
printf("*(p + %d) = %lf\n", i, *(p+i) );
free(p); // Un-reserve the first array
putchar('\n');
p = calloc(4, sizeof(double) ); // Make a NEW double array of 4 elements
// ***** Notice that the array size has CHANGED !!! ****
for ( i = 0; i < 4; i++ )
*(p + i) = i*i; // put value i*i in array element i
for ( i = 0; i < 4; i++ )
printf("*(p + %d) = %lf\n", i, *(p+i) );
free(p); // Un-reserve the second array
}