Allocating Multidimensional Arrays

Allocating Multidimensional Arrays

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];}

Share the Post:
data observability

Data Observability Explained

Data is the lifeblood of any successful business, as it is the driving force behind critical decision-making, insight generation, and strategic development. However, due to its intricate nature, ensuring the

Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular