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]);
}
//---------------------------------------------------------------------------

Recommended Answers

All 4 Replies

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.

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];

commented: Nice +20

ur right ill change it!! thanks u very much!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.