alloc 2d array with new

A

aurgathor

I'm trying to allocate a 2d array in runtime
that can subsequently be accessed like
arr[x][y], to no avail. Is there any to
do that in C++? If yes, how?

TIA

This is what I got thus far:

#include <iostream>

struct sq_T {
short X;
short Y;
int ID;
};

void maker ( int x, int y ) {
sq_T *display = new sq_T[x*y];

// test code
for (int j = 0; j < y; j++)
for (int i = 0; i < x; i++)
display[(j * x) + i].ID = i + (j*x);

for (int j = 0; j < y; j++) {
for (int i = 0; i < x; i++) {
cout << display[(j * x) + i].ID << " ";
}
cout << endl;
}
}


void main () {
maker(5,7);
}
 
A

Axter

aurgathor said:
I'm trying to allocate a 2d array in runtime
that can subsequently be accessed like
arr[x][y], to no avail. Is there any to
do that in C++? If yes, how?

TIA

This is what I got thus far:

#include <iostream>

struct sq_T {
short X;
short Y;
int ID;
};

void maker ( int x, int y ) {
sq_T *display = new sq_T[x*y];

// test code
for (int j = 0; j < y; j++)
for (int i = 0; i < x; i++)
display[(j * x) + i].ID = i + (j*x);

for (int j = 0; j < y; j++) {
for (int i = 0; i < x; i++) {
cout << display[(j * x) + i].ID << " ";
}
cout << endl;
}
}


void main () {
maker(5,7);
}


Check out the following link:
http://www.tek-tips.com/faqs.cfm?fid=5575

It has several more efficient methods for creating 2D array.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top