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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with 2-dim array if poss....

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Hi all,

Iam trying to use a 2-dimensional array [x][y] in which I need to dynamically allocate the x-dimension.

I have created the array as follows:
...
x = tmp;
#define MAX_LINE_LENGTH 500
char (*styledata)[MAX_LINE_LENGTH];
styledata = new char[x][MAX_LINE_LENGTH];

which I thought was alright. I then want to copy a string into each element of the array which I have attempted to do
by accessing a pointer to that element as follows:

char *dataptr;
for (int i=0;i=y;++i)
{ dataptr = &styledata[0];
strcpy(dataptr,appropriate string);
}

This UAE's.
Been staring at it for a while now and either I'm missing the blindingly obvious, have approached the whole thing wrongly or it's kinda subtle.

Can anyone shed some light on this...
Thx for your time.
Iain.
iaincliffe@hotmail.com
 
Hi

You don't tell if you are using MFC. Otherwise, I strongly suggest to use an array of CString. It's much more easy to use, debug and have a lot of powerful functions.

Thierry
 
Try to use this:

...
x = tmp;
#define MAX_LINE_LENGTH 500
char (*styledata)[MAX_LINE_LENGTH];
styledata = new char[x][MAX_LINE_LENGTH];

for(int i=0;i < x;i++)
{
strcpy(styledata,appropriatestring);
}
delete [] styledata;
 
TGM: MFC is unecessary in this particular example. It's got too much overhead that al'thor doesn't need.

Leibnitz: I gave him pretty much the same reply in the Microsoft:C++ forum, but why delete the array? Shouldn't you wait till you're done with it? Maybe you meant delete it later but that's a little ambiguous. MYenigmaSELF:-9
myenigmaself@yahoo.com
 
Here is the correct code:
...
x = tmp;
#define MAX_LINE_LENGTH 500
char (*styledata)[MAX_LINE_LENGTH];
styledata = new char[x][MAX_LINE_LENGTH];

for(int i=0;i < x;i++)
{
strcpy(styledata,appropriatestring);
}
..
....
......
delete [] styledata;
 
Just a side point... it's good to always test whether the memory allocation succeeded before trying to use the variable; something like this:
[ignore]
x = tmp;
#define MAX_LINE_LENGTH 500
char (*styledata)[MAX_LINE_LENGTH];
styledata = new char[x][MAX_LINE_LENGTH];

if (styledata != '\0')
{
for(int i=0;i < x;i++)
{
strcpy(styledata,appropriatestring);
}
..
....
......
delete [] styledata;
}
[/ignore]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top