Reputation: 1
I have a 15x15 array which I have to traverse with pointers (hw ). I'm writing a puzzle solver and I need to search some words vertically,I've done horizontal search but I can't traverse the array column by column.I am trying to assign ptr to tmp each time after tmp reached the end of column.
void VerticalSearch(char** puzzleArray, searchedWord* word) {
int len = word->wordLength;
char **tmp = puzzleArray;
char *ptr = &puzzleArray[0][0];
string s;
for (int i = 0; i < 15; i++) {
**tmp = *ptr;
s = "";
for (int k = 0; k < 15; k++)
{
s += **tmp;
(tmp)++;
}
cout << s << endl;
ptr++;
}
}
Upvotes: 0
Views: 594
Reputation: 2221
To actually do what you need, you have to exploit the way in which the array is allocated in memory.
I'll assume you actually allocate the array on the stack (char puzzle[15][15]
somewhere in your main). In this case, even though passing it to this function will give you a warning (see this answer ) it might work.
The array is allocated in a row-major form, which means that
a1, a2, a3,
b1, b2, b3,
c1, c2, c3
becomes in memory
a1,a2,a3,b1,b2,b3,c1,c2,c3
So you can actually do something like
void VerticalSearch(char** puzzleArray, searchedWord* word) {
int len = word->wordLength;
char** tmp; // initialize the pointer
string s;
for (int i = 0; i < 15; i++) {
tmp = puzzleArray + i; // update with the i-th char of the first row
s = "";
for (int k = 0; k < 15; k++){
s += *tmp;
tmp += 15; //each time you read a character from the column
// go to the next character of the same column
// one row far
}
cout << s << endl;
}
}
This should work, I have not tried it.
By the way, AVOID using pointer arithmetics if you can, in general, and on arrays in particular, it can give severe headaches and lead to bugs. Use usual array indexing and let the compiler take care of this stuff.
For more information on how the matrix is saved in memory, see this
Upvotes: 2