简体   繁体   中英

Using pointers to traverse multidimensional array column by column

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++;          

}   
} 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM