简体   繁体   English

使用指针逐列遍历多维数组

[英]Using pointers to traverse multidimensional array column by column

I have a 15x15 array which I have to traverse with pointers (hw ). 我有一个15x15数组,必须使用指针(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. 我正在写一个谜题求解器,我需要垂直搜索一些单词,我已经进行了水平搜索,但是我无法逐列遍历数组。我试图在tmp到达末尾时每次将ptr分配给tmp柱。

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). 我假设您实际上是在堆栈上分配了数组( char puzzle[15][15]在您的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 关于矩阵是如何保存在内存的详细信息,请参阅

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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