// 24T3 Week 7 Lecture 1 // 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); print_array(data, num_elements); 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\n", nums[i]); } }