In c++ you have the choice of using either new operator or malloc() function to allocate that memory. new is preferred in c++ but malloc() may be a better solution when you need to change the size of the array while the program is running.
An array of pointers to strings that can be resized at any time is declared like this: [icode]char **array[/b]. to allocate memory for 20 strings
char **array = (char **)malloc(20 * sizeof(char **));
now, if you want to expand it to 30 strings array = (char **)realloc(array, 30 * sizeof(char **));
Similar thig can be done usingnew but you have to write your own realloc() function.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
Just use a vector of strings.
I would normally agree but I don't think the OP has that option. This may be an assignment that teaches pointers, not vectors.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
I would normally agree but I don't think the OP has that option. This may be an assignment that teaches pointers, not vectors.
Ah yes, you are probably right.
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
What do you meen "my own realloc"
c++ does not have the equivalent of the realloc() function, which allocates a new pointer, copies the data from the old pointer to the new pointer, then deletes the old pointer. And you can't use realloc() if you usednew. So you would have to write your own function that does the same thing as realloc() but uses the new and delete operators.
And please how do you declare and define the pointer.
I already showed you that in my previous post.char **array declares an array of pointers to strings, which is the purpose of the two asterisks.
The program needs to have a main and functions
Yes, all (or most) c++ programs must have a main function.
Now, start writing your program and posting code if you need more help.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
if you declare the pointer in main() then just pass it by reference to the other functions that need it, just as you would any other parameter.
There are two ways you can do this: pass a pointer to the array -- see the tripple stars in the declaraction. That means its a pointer to a 2d array.
char **foo( char*** array, size_t size)
{
*array = new char*[size];
}
int main()
{
char **array = 0;
foo( &array, 10 );
}
Or use the c++ reference operator &, which simplifies all those asterisks
char **foo( char**& array, size_t size)
{
array = new char*[size];
}
int main()
{
char **array = 0;
foo( array,10 );
}
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343