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 do you create a 2d runtime array

Status
Not open for further replies.

Maulkin

Programmer
Apr 8, 2002
19
AU
trying to create a two dimensional array of strings using malloc.

I use this line to try and create a 2d array of strings

char a[256];
char b*

b = malloc(10 * sizeof(a));

this should create an array of ten rows where each row contains a string of up to 256 characters.

if this is correct do I access elements like this

b[0][0] = k
etc..
 
In that case you need to make 'b' char**.

//'b' is also an array of char* with 10 elem.
char** b = (char **)malloc(10 * sizeof(char *));

//because each slot in b is a char* and 'a' also
//you can do...
b[0] = a;

//but you can also allocated space on each 'b' char*
//for a string

int i=0;
while(i < 10){
//alloc 256 chars on each of those char*
b = (char *)malloc(256 * sizeof(char));

//my compiler zeroes out any allocates space
//but to be save you can do it yourself...
memset(b, 0, 256);

i++;
}
//but now you need to be aware not to do
b[0] = a;
//as you loose the pointer given by malloc
//so you cannot free it like this...

int i=0;
while(i < 10)
//free each char*
free(b[i++]);

//free the char**
free(b);
 
Oops...small correction here!
the first while loop needs to be:

int i=0;
while(i < 10){
//alloc 256 chars on each of those char*
b = (char *)malloc(256 * sizeof(char));

//my compiler zeroes out any allocates space
//but to be save you can do it yourself...
memset(b, 0, 256);

i++;
}
 
I tryed to make a correction but this text field editor is a little buggy, and I probably did it right the first time.

Anyway, in the while loop all 'b' needs to be replaced with 'b'.
 
Thank you
happy.gif
.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top