// This is a second example of how you should create arrays. // In particular, look at functions make_array and copy_array, // and how they respectively create arrays x and result. // Compare to bad_example2.cpp. #include #include int * make_array(int length) { // bad way // int x[2]; // good way int * x = (int *) malloc(sizeof(int) * length); x[0] = 10; x[1] = 20; return x; } int * copy_array(int * source, int length) { // bad way // int result[length]; // good way int * result = (int *) malloc(sizeof(int) * length); int i; for (i = 0; i < length; i++) { result[i] = source[i]; } return result; } int main() { int * x = make_array(2); int * y = copy_array(x, 2); printf("x[0] = %d\n", x[0]); free(x); free(y); return 0; }