473,763 Members | 5,466 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Single dim array as a multidim array?

Please could someone tell me how to use a single-dimensional array as a
two-dimensional array? Is the following correct:

int ROW_SIZE = 5;
int COL_SIZE = 3;

int *arr = (int*) malloc(sizeof(i nt) *ROW_SIZE*COL_S IZE);

arr[i *COLUMN_SIZE + j];

will this only work for square arrays or all two-dim arrays ? Thanks :)
Sona

Jul 19 '05 #1
10 5463
Sona <so**********@n ospam.net> wrote in
<3f********@cla rion.carno.net. au>:
Please could someone tell me how to use a single-dimensional array as a
two-dimensional array? Is the following correct:

int ROW_SIZE = 5;
int COL_SIZE = 3;

int *arr = (int*) malloc(sizeof(i nt) *ROW_SIZE*COL_S IZE); Nit1: arr isn't an array, albeit you can apply the [] operator
to an pointer to int (which it is).

Nit2: the cast to int* is superfluous in C.

arr[i * COLUMN_SIZE + j]; This will work as long as i is in [0 ; ROW_SIZE-1]
and j is in [0 ; COL_SIZE-1].

Much like in a RealArray(tm):

int realArr[YDIM][XDIM];
realArr[ y ][ x ] ...

will this only work for square arrays or all two-dim arrays ? Thanks :)

Well, for square arrays i and j are interchangeable , as long as
you use them in a consistently, but it works for all n-dimensional
arrays, e.g.:

int *arr = (int*) malloc( ZDIM * YDIM * XDIM * sizeof *arr );

arr[ z * XDIM * YDIM + y * XDIM + x ] = 42;

Irrwahn

--
If it's not on fire, it's a software problem.
Jul 19 '05 #2
Irrwahn Grausewitz <ir*****@freene t.de> wrote in
<l9************ *************** *****@4ax.com>:
Well, for square arrays i and j are interchangeable , as long as
you use them in a consistently, but it works for all n-dimensional ^^^^<del>
int *arr = (int*) malloc( ZDIM * YDIM * XDIM * sizeof *arr );

^^^^^^
Damn, now I've copied this stupid cast!

--
Learn how to splel, dmanit!
Jul 19 '05 #3
Irrwahn Grausewitz <ir*****@freene t.de> writes:
Irrwahn Grausewitz <ir*****@freene t.de> wrote in
<l9************ *************** *****@4ax.com>:
Well, for square arrays i and j are interchangeable , as long as
you use them in a consistently, but it works for all n-dimensional

^^^^<del>

int *arr = (int*) malloc( ZDIM * YDIM * XDIM * sizeof *arr );

^^^^^^
Damn, now I've copied this stupid cast!


That's ok. Weirdos who compile your code on boxen where int and int*
are not the same size deserve undefined behavior. Especially if
you forgot to include a header. Remember, all the world is a
wintel32.

(Note to c.l.c++ readers: that cast isn't necessary or safe in C++
either; the alternatives are:
vector<int> arr(ZDIM * YDIM * XDIM);
int *arr= new [ZDIM * YDIM * XDIM * sizeof *arr];
int *arr= static_cast<int *> malloc( ZDIM * YDIM * XDIM * sizeof *arr );
)

Jul 19 '05 #4
Sona wrote:
Please could someone tell me how to use a single-dimensional array as a
two-dimensional array? Is the following correct:

int ROW_SIZE = 5;
int COL_SIZE = 3;

int *arr = (int*) malloc(sizeof(i nt) *ROW_SIZE*COL_S IZE);

arr[i *COLUMN_SIZE + j];

will this only work for square arrays or all two-dim arrays ? Thanks :)


Consider the following C++ program

<example>
void foo(int **b, int rows, int cols)
{
for (int r = 0; r < rows; ++r) {
for (int c = 0; c < cols; ++c) {
b[r][c] = r*c + c;
}
}
}

int main()
{
int rows = 5;
int cols = 3;
int **a = 0;

try {
a = new int*[rows];
a[0] = 0;
a[0] = new int[rows * cols];
for (int r = 1; r < rows; ++r)
a[r] = a[r-1] + cols;

// use the "2D array" 'a' here
foo(a, rows, cols);
}
catch (...) {
// whatever
}

// house keeping
if ( a ) {
delete[] a[0];
delete[] a;
}

return 0;
}
</example>

--
Jim

To reply by email, remove "link" and change "now.here" to "yahoo"
jfischer_link58 09{at}now.here. com
Jul 19 '05 #5
Irrwahn Grausewitz wrote:
Sona <so**********@n ospam.net> wrote in
<3f********@cla rion.carno.net. au>:

Please could someone tell me how to use a single-dimensional array as a
two-dimensional array? Is the following correct:

int ROW_SIZE = 5;
int COL_SIZE = 3;

int *arr = (int*) malloc(sizeof(i nt) *ROW_SIZE*COL_S IZE);


Nit1: arr isn't an array, albeit you can apply the [] operator
to an pointer to int (which it is).

Nit2: the cast to int* is superfluous in C.


It's a bit worse than superfluous. It can be dangerous (as can any cast).

It's necessary in C++, but in C++ you normally shouldn't use 'malloc' at
all. In nearly all cases you should use 'new' instead.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Jul 19 '05 #6
Kevin Goodsell <us************ *********@never box.com> wrote in
<3f539667@shkne ws01>:

It's necessary in C++, but in C++ you normally shouldn't use 'malloc' at
all. In nearly all cases you should use 'new' instead.

From the use of malloc() in the OP's example I derived that this was a
C-question - though it was cross-posted to c.l.c and c.l.c++, like your
reply, and mine too...

--
I wish life had a scroll-back buffer.
Jul 19 '05 #7


Sona wrote:
Please could someone tell me how to use a single-dimensional array as a
two-dimensional array? Is the following correct:

int ROW_SIZE = 5;
int COL_SIZE = 3;

int *arr = (int*) malloc(sizeof(i nt) *ROW_SIZE*COL_S IZE);

arr[i *COLUMN_SIZE + j];

will this only work for square arrays or all two-dim arrays ? Thanks :)


I like:
int i, **arr;
arr = malloc(sizeof(* arr)*ROW_SIZE);
for(i = 0;i < ROW_SIZE; i++)
arr[i] = malloc(sizeof(* *arr)*COL_SIZE) ;
arr[4][2] = 6; /* assuming successful allocations */

This is only one of various ways you can do this. The faq
demonstrates this technique and others at:
http://www.eskimo.com/~scs/C-faq/q6.16.html

--
Al Bowers
Tampa, Fl USA
mailto: xa*@abowers.com base.com (remove the x)
http://www.geocities.com/abowers822/

Jul 19 '05 #8
foo
llewelly <ll*********@xm ission.dot.com> wrote in message news:<86******* *****@Zorthluth ik.local.bar>.. .
Irrwahn Grausewitz <ir*****@freene t.de> writes:
Irrwahn Grausewitz <ir*****@freene t.de> wrote in
<l9************ *************** *****@4ax.com>:
Well, for square arrays i and j are interchangeable , as long as
you use them in a consistently, but it works for all n-dimensional ^^^^<del>
int *arr = (int*) malloc( ZDIM * YDIM * XDIM * sizeof *arr );

^^^^^^
Damn, now I've copied this stupid cast!


That's ok. Weirdos who compile your code on boxen where int and int*
are not the same size deserve undefined behavior. Especially if
you forgot to include a header. Remember, all the world is a
wintel32.

(Note to c.l.c++ readers: that cast isn't necessary or safe in C++
either; the alternatives are:
vector<int> arr(ZDIM * YDIM * XDIM);
int *arr= new [ZDIM * YDIM * XDIM * sizeof *arr];
int *arr= static_cast<int *> malloc( ZDIM * YDIM * XDIM * sizeof *arr );
)

IMHO, a better C++ alterantive would be to use either a
vector<vector<i nt> > object or even better yet, the following dynamic
2 dimensional array object:
template < class T, int ROW_T = 0, int COL_T = 0 >
class dynamic_2d_arra y
{
public:
dynamic_2d_arra y(int row, int col):m_row(row) ,m_col(col),
m_data((row!=0& &col!=0)?new T[row*col]:NULL){}
dynamic_2d_arra y():m_row(ROW_T ),m_col(COL_T), m_data(new
T[ROW_T*COL_T])
{if (!COL_T || !ROW_T) {int x[ROW_T] = {{ROW_T}};int y[COL_T] =
{{x[0]}};}}
~dynamic_2d_arr ay(){if(m_data) delete []m_data;}
T* operator[](int i) {return (m_data + (m_col*i));}
T const*const operator[](int i) const {return (m_data +
(m_col*i));}
private:
const int m_row;
const int m_col;
T* m_data;
};
See following link for usuage example and for vector<vector<t ype> >
example:

http://axter.com/faq/topic.asp?TOPIC..._ID=4&CAT_ID=9
Jul 19 '05 #9
ma*******@axter .com (foo) wrote in
<c1************ **************@ posting.google. com>
a lot of semi-cryptical C++ code. Please do not cross-post
C++ stuff to c.l.c.
--
When things look dark,
hold your head high so it can rain up your nose.
Jul 19 '05 #10

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

Similar topics

4
1716
by: somaboy mx | last post by:
Hello, I need to do the following: Say I have a multidim array: $array = array(); $array = 'Kevin';
8
1912
by: Levent | last post by:
Hi, Is it possible to have static multi-dim array as a function return parameter? in particular, class Foo { int arr; public: ? getArr() {return (?) arr;}
10
1288
by: Sona | last post by:
Please could someone tell me how to use a single-dimensional array as a two-dimensional array? Is the following correct: int ROW_SIZE = 5; int COL_SIZE = 3; int *arr = (int*) malloc(sizeof(int) *ROW_SIZE*COL_SIZE); arr;
2
2099
by: Salman Khilji | last post by:
After reading all the FAQs, I cannot solve the following problem: I have a pointer of type double. I am supposed to 1) Allocate memory for it assuming that the pointer will be pointing to a multi-dimensional array whose dimensions will be specified at run-time. 2) Set the individual elements of the array using pointer-arithmetic.
1
1630
by: Abhi | last post by:
Hi! I am wondering if someone can point me to the needed sort function. There are so many of them that I simply got lost by reading their descriptions. I try to explain what I need. I have a multidimensional array and I have a function that outputs it as a table. $arr contains an array that contains usernames $arr contains an array that contains real names $arr contains an array that contains e-mails
0
1397
by: guerrerofarias | last post by:
I have a "population" of objects that is suppose to do a lot of stuff during its lifecycle... I had everything working fine (not fancy code, though) with an array, but now I've received instructions to let the population change size over generations. This means my array no longer works...I want to change it to a vector (or map), keeping the basic structure of the code. But it beats my skills...I read a thread...
1
828
by: Astha | last post by:
Hi. I am having a problem when retrieving data from database and comparing each of them to decide wheter or not to give access to a user to a certain page.Actually,the data being retrieved are checkbox values..there are four checkboxes under one category..there are six category altogether...so 24 checkboxes altogether.I have to use multidim array...i guess...bt am very confused abt it.Pls can anyone help me out!
31
1911
by: mdh | last post by:
I am still having a problem understanding K&RII on p 112. I have looked at the FAQs --which I am sure answer it in a way that I have missed, so here goes. A 2-dim array, (per K&R) is really a 1-dim array, each of whose elements is an array. Looking at the debugger I use, arr is shown as an initial value of "2", but when expanded, there are 2 consecutive arrays of 13 elements. So, may I ask this? Is there anything special that marks the...
152
9887
by: vippstar | last post by:
The subject might be misleading. Regardless, is this code valid: #include <stdio.h> void f(double *p, size_t size) { while(size--) printf("%f\n", *p++); } int main(void) { double array = { { 3.14 }, { 42.6 } }; f((double *)array, sizeof array / sizeof **array); return 0;
0
10002
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...
1
9938
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9823
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8822
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
6643
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
5270
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
5406
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3528
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2794
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.