Hi,
I seem to have a problem with an 2D arrray. I want to create an 2D AnsiString array (AnsiString array[][] ). I can compile it but i get an acces violation when i try to put value in the array.

I changed the AnsiString to integers witch works fine but that's not what i need.
I know you can make an 2D array AnsiString like this :

AnsiString array[3][7];

but i dont know the values before run-time so i used malloc.

Can someone help me understand what is going wrong? And maiby help me on an solution?

Thanks!!

This is the code that gives acces violation in run-time:

//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "test23.h"
#include <string>
using namespace std;
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
	: TForm(Owner)
{
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button1Click(TObject *Sender)
{
int nrows = 7, ncolumns =3, i, iTel, iCount;

	AnsiString **array;
	array = (AnsiString **)malloc(nrows * sizeof (int*));
	for(i = 0; i < nrows;i++)
		array[i]= (AnsiString *)malloc(ncolumns * sizeof(int));

for(iTel=0;iTel<=2;iTel++)
	for(iCount=0;iCount<=6;iCount++)
	 array[iTel][iCount] = "100";

	ShowMessage(array[2][3]);
}
//---------------------------------------------------------------------------

You can not call malloc() to allocate c++ classes. It doesn't work. Use the c++ new operator. You have to call either delete or delete[] to destroy it.

Edited 6 Years Ago by Ancient Dragon: n/a

Thank man!! got it working now!!!

I know use the following code:

AnsiString **array = new AnsiString*[nrows * sizeof (int*)];
	for(i = 0; i < nrows;i++){
		array[i]= new AnsiString[ncolumns * sizeof(int)];
	   //AnsiString array[3][7];
		}
for(iTel=0;iTel<=2;iTel++)//for loop voor field te selecteren.
	for(iCount=0;iCount<=6;iCount++){//for loop voor record te selecteren.
	 //ShowMessage("hallo");
	 array[iTel][iCount] = "100";
	}
	ShowMessage(array[1][3]);
 for (int i = 0; i < nrows; ++i)
	delete [] array[i];
  delete [] array;

Why are you multiplying nrows * sizeof(int*)? AnsiStriong is not an int pointer, so that doesn't make any sense.

>>AnsiString **array = new AnsiString*[nrows * sizeof (int*)];

^^^ Wrong AnsiString **array = new AnsiString*[nrows]; >>array= new AnsiString[ncolumns * sizeof(int)];

^^^ Wrong array[i]= new AnsiString[ncolumns];

Edited 6 Years Ago by Ancient Dragon: n/a

Comments
Nice
This question has already been answered. Start a new discussion instead.