dynamic array 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: 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 3: allocate memory c
ptr = (castType*)calloc(n, size);
Example 4: 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);
Example 5: c infiite array
int main(int argc, char *argv[])
{
int i;
double* p;
p = calloc(10, sizeof(double) );
for ( i = 0; i < 10; i++ )
*(p + i) = i;
for ( i = 0; i < 10; i++ )
printf("*(p + %d) = %lf\n", i, *(p+i) );
free(p);
putchar('\n');
p = calloc(4, sizeof(double) );
for ( i = 0; i < 4; i++ )
*(p + i) = i*i;
for ( i = 0; i < 4; i++ )
printf("*(p + %d) = %lf\n", i, *(p+i) );
free(p);
}
Example 6: how to use malloc in c
ptr = (castType*) malloc(size);