Article View: hepnet.lang.c++
Article #4Re: dynamicaly allocating a two dim. array
From: Peter Dennis
Date: Sun, 22 Oct 1995 11:18
Date: Sun, 22 Oct 1995 11:18
76 lines
2226 bytes
2226 bytes
In article <dqua.813429186@dqua>,
dqua@earthlink.net (Derick J.R. Qua-Gonzalez) wrote:
>btrojano@chat.carleton.ca (Bart Trojanowski) writes:
>
>>I desperately need help. My assignment is due very soon.
>
>This shouldn't be in c.l.c. But since you xposted to C++ as wel...
>
>>What I need to do is allocate memory for the following....
>> float array[x][y];
>>but dinamicaly, ie the user specifies how large it must be.
>
>>float = **array;
> |
> |
> WHAT?
>
Hope my idea will help you! (No guarantees on correctness)
but...
If I understand your problem, you want to make a two dimensional array
of
floats by using new after you get the two indeces from the user?
user enters x and y(two ints)
if you declare array a pointer to a float...
float *array;
then use new as follows...
In c++...
array = new float[x*y];
In c...
array = (float*) malloc(sizeof(float)*x*y);
this should create an array of floats in memory which you can be used
like this(I think)
array[a*y+b] where as array[a][b] is what you want.
float *array;
x = 3;
y = 4;
array = new float[x*y];
/* assign array[2][3] to be 3.14159 */
array[2*y + 3] = 3.14159;
in c++...
cout << "array[" << 2 << "][" << 3 << "] = " << array[2*y+3] << endl;
or
cout << "array[2][3] = " << array[2*y+3] << endl;
in c...
printf("array[%d][%d] = %f\n", 2, 3, array[2*y + 3] );
or
printf("array[2][3] = %f\n", array[2*y +3] );
output should be...
with printf in c I got
array[2][3] = 3.141590
with cout in c++ I got
array[2][3] = 3.14159
to work with array[a][b] in array[x][y] just use array[a*y+b]
Hope I didn't screw up somewhere.
Use this information at your own risk.
TechMan2@ix.netcom.com
Technical Details
Message-ID:
<46d9ak$c5h@ixnews7.ix.netcom.com>Path:
arc1-ca.pugleaf.net!ix.netcom.com!netnewsReferences:
<DG7ExA.3CG@cunews.carleton.ca> <dqua.813429186@dqua>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!ix.netcom.com!netnews From: techman2@ix.netcom.com (Peter Dennis ) Newsgroups: hepnet.lang.c++,comp.lang.c,comp.lang.c++,cern.c++ Subject: Re: dynamicaly allocating a two dim. array Date: 22 Oct 1995 11:18:44 GMT Organization: Netcom Message-ID: <46d9ak$c5h@ixnews7.ix.netcom.com> References: <DG7ExA.3CG@cunews.carleton.ca> <dqua.813429186@dqua> NNTP-Posting-Host: ix-ham-oh1-08.ix.netcom.com X-NETCOM-Date: Sun Oct 22 4:18:44 AM PDT 1995