472,338 Members | 1,695 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,338 software developers and data experts.

Multi-dimensional array allocation with single 'new' call

I used to work with C and have a set of libraries which allocate
multi-dimensional arrays(2 and 3) with single malloc call.

data_type **myarray
= (data_type**)malloc(widht*height*sizeof(data_type) + height*
sizeof(data_type*));

//allocate individual addresses for row pointers.

Now that I am moving to C++,am looking for something by which I can
allocate a
multi-dimensional array with one (and only one) 'new' call.

Does my old libraries (with malloc calls) work in C++.Yes.

Then why do I want to use 'new'.Some books encourage usage of new to
malloc(I assume new is much safer than malloc). Anyways,can this be
done?Has anybody done it ?

Thanks,in advance, for all your help.

Ram
Jul 22 '05 #1
2 7524
ip****@yahoo.com wrote:
I used to work with C and have a set of libraries which allocate
multi-dimensional arrays(2 and 3) with single malloc call.

data_type **myarray
= (data_type**)malloc(widht*height*sizeof(data_type) + height*
sizeof(data_type*));

//allocate individual addresses for row pointers.

Now that I am moving to C++,am looking for something by which I can
allocate a
multi-dimensional array with one (and only one) 'new' call.

Does my old libraries (with malloc calls) work in C++.Yes.

Then why do I want to use 'new'.Some books encourage usage of new to
malloc(I assume new is much safer than malloc). Anyways,can this be
done?Has anybody done it ?

Thanks,in advance, for all your help.


In C++, you don't need any new calls. Consider this:

#include <vector>

template <typename w_elem_type>
class matrix
{
public:
typedef int t_Size;

t_Size m_columns;
t_Size m_rows;

std::vector<w_elem_type> m_data;

matrix( t_Size i_columns = 0, t_Size i_rows = 0 )
: m_columns( i_columns ),
m_rows( i_rows ),
m_data( i_columns * i_rows )
{
}

w_elem_type * operator[]( t_Size i_index )
{
return & ( m_data[ i_index * m_rows ] );
}

template <typename w_Type, int w_columns, int w_rows>
matrix( const w_Type (&i_array)[w_columns][w_rows] )
: m_columns( w_columns ),
m_rows( w_rows ),
m_data( & (i_array[0][0]), & (i_array[w_columns-1][w_rows]) )
{
}

};

#include <iostream>

double array[3][4] = {
{ 1.0, 2.0, 3.3, 4.4 },
{ 1.0, 2.0, 3.3, 4.4 },
{ 1.0, 2.0, 3.3, 4.5 },
};

int main()
{
matrix<float> mat1( 3, 4 );
matrix<float> mat2;
// convert a double array to a float matrix (on the fly!)
matrix<float> mat3( array );

mat2 = mat3;

std::cout << mat2[2][3] << "\n";
}
How would you do this with malloc ?
Jul 22 '05 #2
ip****@yahoo.com wrote:
I used to work with C and have a set of libraries which allocate
multi-dimensional arrays(2 and 3) with single malloc call.

data_type **myarray
= (data_type**)malloc(widht*height*sizeof(data_type) + height*
sizeof(data_type*));
Note that you are allocating two separate data structures at once:
- the data area for your multi-dimensional array
- an array of pointers to the beginning of the rows

I assume you are then computing and storing the start addresses of the
individual rows. Without measuring the effect, I would actually guess
that the on-the-fly computation of the addresses is not slower than the
pointer look-up. In C++ this can neatly be encapsulated by a suitable
function of an multi-dimensional array class. This is just a separate
issue you might want to consider.
Now that I am moving to C++,am looking for something by which I can
allocate a multi-dimensional array with one (and only one) 'new' call.
It is important to understand the motivation of replacing 'malloc()' by
'new': other than 'malloc()', 'new' calls the constructor of the
respective objects. For POD-types (ie. for built-in types and C-like
structs), this actually does nothing (... and the calls to any form of
constructors are elided, ie. it is in no way a performance hit) but for
class types the necessary initialization is performed. You can use
'malloc()' or its moral C++ equivalent, ie. 'operator new()' or
'operator new[]()', in C++, too, but you have to make sure to call the
relevant constructors and, at destruction time, the relevant
destructors.
Does my old libraries (with malloc calls) work in C++.Yes.
Considering my previous paragraph, I would seriously question your
statement that use of 'malloc()' works properly - unless you are only
using multi-dimensional arrays with POD-types in which case there is
no good reason to rewrite your library to use 'new', IMO.
Then why do I want to use 'new'.Some books encourage usage of new to
malloc(I assume new is much safer than malloc).
Understanding the motivation of any advice is quite important to
understand when to follow the advice. 'new' is no way "safer" than
'malloc()'. For non-POD types 'malloc()' without later explicit
constructor calls (see below) simply does not work!
Anyways,can this be done?Has anybody done it ?


The answers to these questions are "kind of" and "yes". The purpose of
using 'new' is to invoke the constructors for the objects. Likewise,
the purpose of 'delete' is to invoke the destructors for the objects.
That is, in addition to the memory management operations, of course.
Although C++ does not provide an immediate approach to the creation of
inhomogenous areas of memory, it provides a manual approach under the
name of "placement new". The idea is to split the operation into its
two components:

- memory management (memory allocation of 'new' and memory release for
'delete')
- object life-time maintenance, ie. construction of 'new' and
destruction for 'delete'.

Whether you are using 'operator new()' and 'operator delete()' (or, if
you prefe, 'operator new[]()' and 'operator delete[]()') or 'malloc()'
and 'free()' for the memory management, does not really matter. However,
you need to use placement-new and placement-delete for the other
component.

Here is some code to illustrate this (normally, this code would be
encapsulated into an appropriate class):

// header for placement-new function:
#include <new>

// obtain the memory with just one call:
void* mem = operator new(width * height * sizeof(data_type)
+ height * sizeof(data_type*));

// initialize the data area:
data_type* array = static_cast<data_type*>(mem);
// the C++ approach to initialization is actually this:
// std::uninitialized_fill(array, width * height, data_type());
// ... but for demonstraction here is a similar, though semantically
// slightly different approach (*):
for (data_type* cur = array, end = array + width * height;
cur != end; ++cur)
new(cur) T();

// initialize the row pointers:
typedef data_type* data_type_ptr; // (**)
data_type** rows = reinterpret_cast<data_type**>(
reinterpret_cast<char*>(mem) + width * height * sizeof(data_type);
for (std::size_type i = 0; i != height; ++i)
new(rows[i]) data_type_ptr(array + i);

// use the array

// destroy the row pointers:
for (std::size_type i = height; --i; )
row[i].~data_type_ptr();

// destroy the data area:
for (data_type* cur = array + width * height; array != cur; )
(--cur)->~data_type();

// release the memory:
operator delete(mem);

Comments:
* The semantic difference is that 'uninitialized_fill()' uses the
copy constructor on the passed object while the explicit loop
uses the default constructor for each object.
** I'm not sure whether this typedef is necessary for the construction
(I think it is not) but it is necessary for the destruction.

Conclusions:
- Yes, it is possible.
- I don't think it is worth the hassel:
- the array of row pointers is probably only good to decrease
performance, both during construction and use
- even if you insist in using this array, it is easier to use
multiple allocations and I seriously doubt that you will be
able to measure the difference for any reasonable sized array.
--
<mailto:di***********@yahoo.com> <http://www.dietmar-kuehl.de/>
<http://www.contendix.com> - Software Development & Consulting
Jul 22 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: OutsiderJustice | last post by:
Hi All, I can not find any information if PHP support multi-thread (Posix thread) or not at all, can someone give out some information? Is it...
37
by: ajikoe | last post by:
Hello, Is anyone has experiance in running python code to run multi thread parallel in multi processor. Is it possible ? Can python manage...
4
by: Frank Jona | last post by:
Intellisense with C# and a multi-file assembly is not working. With VB.NET it is working. Is there a fix availible? We're using VisualStudio...
12
by: * ProteanThread * | last post by:
but depends upon the clique: ...
6
by: Joe | last post by:
I have 2 multi-list boxes, 1 displays course categories based on a table called CATEGORIES. This table has 2 fields CATEGORY_ID, CATEGORY_NAME ...
4
by: mimmo | last post by:
Hi! I should convert the accented letters of a string in the correspondent letters not accented. But when I compile with -Wall it give me: ...
5
by: dkelly925 | last post by:
Is there a way to add an If Statement to the following code so if data in a field equals "x" it will launch one report and if it equals "y" it...
23
by: Kaz Kylheku | last post by:
I've been reading the recent cross-posted flamewar, and read Guido's article where he posits that embedding multi-line lambdas in expressions is an...
14
by: =?ISO-8859-1?Q?Tom=E1s_=D3_h=C9ilidhe?= | last post by:
As far as I know, the C Standard has no mention of multi-threaded programming; it has no mention of how to achieve multi-threaded programming, nor...
11
by: woodey2002 | last post by:
This problem is driving me crazy. Hello there, i am trying to create a search form for records in my access database. The search form will...
0
by: concettolabs | last post by:
In today's business world, businesses are increasingly turning to PowerApps to develop custom business applications. PowerApps is a powerful tool...
0
better678
by: better678 | last post by:
Question: Discuss your understanding of the Java platform. Is the statement "Java is interpreted" correct? Answer: Java is an object-oriented...
0
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and...
0
by: CD Tom | last post by:
This only shows up in access runtime. When a user select a report from my report menu when they close the report they get a menu I've called Add-ins...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge...
0
jalbright99669
by: jalbright99669 | last post by:
Am having a bit of a time with URL Rewrite. I need to incorporate http to https redirect with a reverse proxy. I have the URL Rewrite rules made...
0
by: Matthew3360 | last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. ...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.