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

2-dim array access problem - or maybe creation problem ;-)

Status
Not open for further replies.

bodhi

Programmer
Jan 3, 2002
67
GB
Hi all,

I am 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:
...blah blah....tmp assigned.
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.

 
Maybe you're a better coder than I but your for loop looks pretty messed up to me. Here's what I would have done:
Code:
char (*styledata)[MAX_LINE_LENGTH]=new char[x][MAX_LINE_LENGTH];

for(int i=0; i<x; i++){
	strcpy(styledata[i],
appropriate string
Code:
);
}

[code]
I'm not sure exactly what you were trying to do, but styledata[0] returns the pointer to the first 'x' position, therefore you don't need to get the address of it.  It is already a char pointer.  Hope that helped.  Good Luck.

p.s.  Depending on weither or not you have to worry about memory, you might want to use calloc and realloc to make the whole thing dynamic.  You can get the size of the string using strlen, then using calloc cast a void* to char* and just create an array of size x of char*s.  Or if you're really good figure out how much memory a char* takes and make a completely dynamic array of char*s to char*s.  Maybe that's overkill.  Anyway, lotsa luck. MYenigmaSELF:-9
myenigmaself@yahoo.com
[URL unfurl="true"]http://myenigmaself.gaiden.com[/URL]
 
oops..<embarrassed cough> - Well, it was definately the first of the three possibilities ;-)

That's exactly what I was looking for...many thanks.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top