Click to See Complete Forum and Search --> : multiple-index character arrays


October 12th, 1999, 09:24 AM
HELP, Please!!!
How do I declare, dynamically create and use a double-subscript array of character pointers??? EX: If it is done statically, I would do this:
char *myarry[num_rows][num_columns];
I don't know how many rows there will be so I want to do it dynamically. The number of columns is fixed at three. The problem is, I'm stupid when it comes to pointers to pointers and dynamic allocation. Can someone show me the light? I thought it should look something like this:
char *buffer = "sentence";
char **words;
words = new char*[rows][3];
words[row][col] = buffer;
but the Microsoft Visual C++ 6.0 compiler won't accept it because the types don't match. What am I doing wrong?

Thanks!
jeff_caswell@techpointer.com

srini_raghav
October 12th, 1999, 09:37 AM
Yeah, I can understand how much u r afraid of pointers.
Ok, lets go like this.
char **temp;
For this I don't know both the limits, means first dimension and second dimension. See how I am allocating memory to this.
temp = (char**)malloc(sizeof(char*)*10);/*By this temp can store 10 char*s*/
then assume
char* example = "srini";
U want to store this as first string in temp, then
*temp = (char*)malloc(strlen(example)+1);
strcpy(*temp,example);

Like this u can continue..

remember that, u should deallocate the memory u have allocated. So u must know the count of strings that is there in the double pointer. To go to next string just increment, temp++, thats it...
U can even index the temp and access as *temp[10]...

Hope u must have understood this... Like this u can even use new to allocate memory...

Thanks,
Srini.

Tufail Khan
October 12th, 1999, 09:41 AM
hello friend,

Have a look at it,

suppose u want to have an array of pointers to pointers of integers,

e.g.
int main(void)
{
int **ptr;

// get an array of pointers to hold the pointers
ptr = new int*[10];

// now assign element a new pointer
ptr[0] = new int;
ptr[1] = new int;
...


// u need to delete each individual poiner
delete ptr[0];
delete ptr[1;

// then u need to delete the array of pointers to // pointers
delete [] ptr;

return 0;
}

Hope u will get it now,

Regards,
Tufail Khan