Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to dinamicaly create a bi-dimensional array

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Hi,

I´d like to dinamicaly create a matrix to implement a linear sistem.

I tried first:
float **matrix;
matrix = new float[10][10];

It didn´t work. Then I tried:

float **matrix;
*matrix = new float[10];
for(int i=0; i<10; ++i)
matrix = new float[10];

It compiled, but when I try matrix[0][0], for example, the program chashes saying it has violated the memory access. Can anyone helpme implement this?

Thanx,
LAC.
 
just a thought. Why not try this

float ** matrix;

*matrix = new float[10*10];

See if that will do it...

the for loop should not have crashed on [0][0] in my opinion but there should have been ALOT of memory leaks.

Matt
 
Are you trying to make the array be different sizes depending on what data you have? If so, I think you would be better using linked lists as you can add extra elements to these on the fly, whereas arrays are fixed size.
 
Sorry,

in my previous message I meant:
float **matrix;
*matrix = new float[10];
for(int i=0; i<10; ++i)
matrix = new float[10];




 
See the thread
thread116-107726 deals with this exact question. In summary, I quote jtm111's solution:

const int Rows = 1000;
const int Cols = 100;

float **matrix;

// Allocate a pointer to an array of floats
matrix = new float *[Rows];

// Allocate each row individually
for (int j = 0; j < Rows; j++)
matrix[j] = new float[Cols];

// Delete each row
for (int j = 0; j < Rows; j++)
delete [] matrix[j];

// Delete the pointer to the array
delete [] matrix;


Vincent
 
Remember that, as of right now, arrays MUST use constants as the arguments (the C99 spec allows VLAs, but I don't know if VC++ supports this at all yet). If you have a known size, it's easy. If not, you'll need another solution.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top