dynamic - Declare the size of array at runtime in standard C (not in C99) -
array needs size defined @ compile time. there possibility define size of array @ runtime using malloc
or whatever?
you can use calloc , malloc or realloc
per requirements. explained here.
the malloc function allocates n bytes of memory, suitably aligned storage of type. pointer suitable passing free, deallocates it, or realloc, changes size (and may move different location). calloc allocates nmemb*size bytes, if malloc, , sets them bits zero.
should noted bits 0 not valid null pointer or floating point 0 calloc cannot relied upon correctly initialise data types.
here code samples
#include<stdlib.h> /* code */ n = some_calculation() ; // array size generated @ runtime // data_type type of array eg. int or struct //using calloc ,it set allocated values 0 or null per data_type data_type *array = calloc(n,sizeof(data_type)) ; // using malloc , allocate adresses, may contain garbage values data_type *array = (data_type *)malloc(n); // using realloc array = (data_type *) realloc(array, new_n); // after have used array , can free memory allocated free(array);
Comments
Post a Comment