In the line
char ** domain[] = new char * [rows];
char ** domain[]
tries to make an array of char **
. If the compiler didn’t complain about not having a valid array size in the []
and you would have a 3D structure. You want just plain old char **
for a 2D structure, so
char ** domain = new char * [rows];
The loop filling out the inner dimension is correct except it loses track of the starting point of domain
for(int i = 0; i < rows; i++)
{
*domain = new char[columns];
domain++;
}
Should be something like
char ** temp = domain;
for(int i = 0; i < rows; i++)
{
*temp = new char[columns];
temp++;
}
To preserve the starting point, but for this case array notation is probably the smarter and easier-to-read option.
for(int i = 0; i < rows; i++)
{
domain[i] = new char[columns];
}
On to searchArray
. It needs to know it’s getting two dimensions, (const char **
) and that there are two max sizes (maxRow
and maxColumn
). It will look something like
char searchArray(const char ** list,
char letter,
int maxRow,
int maxColumn)
{
>code goes here
}
Code goes here is your problem, but will probably be two nested for
loops iterating to maxRow
and maxColumn
and returning when letter
is found.
But… Why return a char
? Returning the location in the array is much more useful. We could use std::pair
, but if std::vector
is off limits, pair
probably is as well. Consider something like the following instead:
struct coord
{
int row;
int column;
};
coord searchArray(const char ** list,
char letter,
int maxRow,
int maxColumn)
{
coord location;
>code goes here
return location;
}
If the item is not found, set row
and column
to something impossible to get like -1 so you can easily test for the not found case.
Stop here unless you want to <expletive deleted> with your teacher’s brain.
The above doesn’t build a 2D array. You can’t get a dynamically allocated 2D array in C++. What you have is an array of arrays. There are a couple downsides to this, look at all the work that goes into stitching one together and computers love it when things go in straight lines. Array of arrays doesn’t. Every different allocation can be somewhere completely different in memory forcing the program to hop around, waiting on and loading different chunks of memory. Sometimes The program will spend more time sitting around waiting for stuff to be found and loaded than it’ll spend doing the actual work. This sucks.
The solution is to make a 1D array and make it look like a 2D array. Here’s an example of that from the C++ FAQ
You’ll learn a lot of neat stuff from following this example, not the least of which being RAII and the Rule of Three, two concepts without which you cannot write non-trivial high quality C++ code.
4
solved How can I use a search function on a dynamic array?