dynamic array in c code example
Example 1: allocate memory c
ptr = (castType*) malloc(size);
int *exampl = (int*) malloc(sizeof(int));
ptr = (castType*) calloc(n, size);
char *exampl = (char*) calloc(20, sizeof(char));
Example 2: how to dynamically allocate array size in c
int *p_array;
double *d_array;
p_array = (int *)malloc(sizeof(int)*50);
d_array = (int *)malloc(sizeof(double)*100);
for(i=0; i < 50; i++) {
p_array[i] = 0;
}
double *dptr = d_array;
for(i=0; i < 50; i++) {
*dptr = 0;
dptr++;
}
Example 3: 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) {
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 4: c malloc array
#define ARR_LENGTH 2097152
int *arr = malloc (ARR_LENGTH * sizeof *arr);
Example 5: allocate memory c
ptr = (castType*)calloc(n, size);
Example 6: C dynamic array
Array a;
int i;
initArray(&a, 5);
for (i = 0; i < 100; i++)
insertArray(&a, i);
printf("%d\n", a.array[9]);
printf("%d\n", a.used);
freeArray(&a);