devxlogo

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

See also  Small Business Strategies with Venmo
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist