Question:
I have two questions about arrays.
I have a 2D array of floats. I want to init everything with 0.0f. There must be a better way than going through it with two for loop, right ?
How do I declare a 2D/3D array on the free store whose size is defined at runtime?
Answer:
You’re right. There is a better way to initialize a multidimensional array of float:
float arf[5][8] = {0.0}; //initialize all elements
You can’t directly allocate multidimensional arrays using new. Instead, create an array of pointers and allocate a subarray for each pointer in the original array using new:
int *pp[8];/*pp is an array of 8 pointers to int*/for (int i=0; i<8; i++){ pp[i] = new int[5]; /* fill subarrays in array of pointers */}pp[0][0] = 10; //..use pp as a 2D arrayfor (int j=0; j<8; j++) // delete subarrays{ delete[] pp[j];}