[英]Using pointers to traverse multidimensional array column by column
我有一個15x15數組,必須使用指針(hw)遍歷。 我正在寫一個謎題求解器,我需要垂直搜索一些單詞,我已經進行了水平搜索,但是我無法逐列遍歷數組。我試圖在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++;
}
}
要實際執行所需的操作,必須利用在內存中分配數組的方式。
我假設您實際上是在堆棧上分配了數組( char puzzle[15][15]
在您的main中的某個位置)。 在這種情況下,即使將其傳遞給此函數將向您發出警告(請參閱此答案 ),它也可能會起作用。
該數組以行優先形式分配,這意味着
a1, a2, a3, b1, b2, b3, c1, c2, c3
成為記憶
a1,a2,a3,b1,b2,b3,c1,c2,c3
所以你實際上可以做類似的事情
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;
}
}
這應該工作,我還沒有嘗試過。
順便說一句,如果可以,尤其是在數組上,如果可以的話,請避免使用指針算法,否則可能會造成嚴重的麻煩並導致錯誤。 使用通常的數組索引,讓編譯器處理這些工作。
關於矩陣是如何保存在內存的詳細信息,請參閱本
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.