// An example of creating an array of a size // determined at run time using malloc #include #include int *create_array(int num_elements); void print_array(int nums[], int size); int main(void) { int num_elements; printf("How many elements? "); scanf("%d", &num_elements); int *data = create_array(num_elements); printf("Original Array: "); print_array(data, num_elements); // Decide we need a bigger array! // Common to double the size or 1.5 the size etc. int new_size = num_elements + 1; data = realloc(data, new_size*sizeof(int)); data[new_size-1] = 9999; //printf("Realloced Array: "); print_array(data, new_size); free(data); return 0; } // returns a pointer to a malloced array int *create_array(int num_elements) { int *data = malloc(num_elements *sizeof(int)); if (data == NULL) { printf("Out of memory\n"); return NULL; } // You can still use array notation!!!! for (int i = 0; i < num_elements; i++) { data[i] = i*10; } return data; } void print_array(int nums[], int size) { for (int i = 0; i < size; i++) { printf("%d ", nums[i]); } printf("\n"); }