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


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

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