473,396 Members | 1,967 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 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 7637
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 supported? If yes, where's the info? If no, 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 which cpu shoud do every thread? Sincerely Yours,...
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 2003 Regards Frank
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 The other multi-list box displays courses based on...
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: warning: multi-character character constant Do the...
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 would open another report. Anyone know how to modify...
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 unsolvable puzzle. So for the last 15 minutes...
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 does it mention whether the language or its...
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 contain text boxes and a multi select list box. The user...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.