dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Beginner
Feb 22, 2000

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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 array

for (int j=0; j<8; j++) // delete subarrays
{
 delete[] pp[j];
}
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date