473,748 Members | 6,034 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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**)ma lloc(widht*heig ht*sizeof(data_ type)+ height*
sizeof(data_typ e*));

//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 7666
ip****@yahoo.co m 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**)ma lloc(widht*heig ht*sizeof(data_ type)+ height*
sizeof(data_typ e*));

//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_e lem_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.co m 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**)ma lloc(widht*heig ht*sizeof(data_ type)+ height*
sizeof(data_typ e*));
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_typ e)
+ height * sizeof(data_typ e*));

// initialize the data area:
data_type* array = static_cast<dat a_type*>(mem);
// the C++ approach to initialization is actually this:
// std::uninitiali zed_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_cas t<data_type**> (
reinterpret_cas t<char*>(mem) + width * height * sizeof(data_typ e);
for (std::size_type i = 0; i != height; ++i)
new(rows[i]) data_type_ptr(a rray + 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.co m> <http://www.dietmar-kuehl.de/>
<http://www.contendix.c om> - 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
14572
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 possible to make doing multi-thread stuff? Thanks. YF
37
4895
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, Pujo
4
4673
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
3879
by: * ProteanThread * | last post by:
but depends upon the clique: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&threadm=954drf%24oca%241%40agate.berkeley.edu&rnum=2&prev=/groups%3Fq%3D%2522cross%2Bposting%2Bversus%2Bmulti%2Bposting%2522%26ie%3DUTF-8%26oe%3DUTF-8%26hl%3Den ...
6
4893
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 a table called COURSES. This table has 2 fields CATEGORY_ID, COURSE_NAME. The CATEGORY_ID is a FK in COURSES and a PK in CATEGORIES. I want to populate the course list box based on any category(s)
4
17873
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 problem is the charset? How I can avoid this warning? But the worst thing isn't the warning, but that the program doesn't work! The program execute all other operations well, but it don't print the converted letters: for example, in the string...
5
3283
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 this? Private Sub cmdPreview_Click() On Error GoTo Err_Handler 'Purpose: Open the report filtered to the items selected in the list box. 'Author: Allen J Browne, 2004. http://allenbrowne.com Dim varItem As Variant 'Selected items
23
5329
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 I applied myself to this problem and come up with this off-the-wall proposal for you people. Perhaps this idea has been proposed before, I don't know. The solutions I have seen all assume that the lambda must be completely inlined within the...
14
3408
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 libraries are suitable for multi-threaded programming. For people who are fond of portable C programming, what's the best way to go about multi-threaded programming? I've been reading up on POSIX threads a little, they seem pretty ubiquitous....
11
5601
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 can enter their search criteria eg. surname, reg num, etc. in the text boxes. The multi select list box allows the user to select multiple counties which they have the option of including in the search. The user should be able to select or omit the...
0
8991
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9370
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8242
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6074
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4602
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4874
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3312
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2782
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2215
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.