[英]Shall a pointer to an array compare equal to a pointer to its first element?
[英]Assigning array to array by having pointer to its first element
我相信這是我的功能(我仍在嘗試適應指針)返回一個指向名為cords
的數組的第一個元素的指針:
int* getPosition( char arr[][5], char letter ) {
int cords[2];
for ( int y = 0; y < 5; y++ ) {
for ( int x = 0; x < 5; x++ ) {
if ( arr[y][x] == letter ) {
cords[0] = x;
cords[1] = y;
}
}
}
return cords;
}
這是我的第二個功能:
string scrambling( char arr[][5], vector<string> *pairs ) {
string encrypted;
int firstCords[2];
...
}
我想以某種方式將函數getPosition
的數組“ cords”中的值分配給函數scrambling()
中的firstCords
數組。
我的臨時解決方案是:
firstCords[0] = getPosition( arr, (*pairs)[i][0] )[0];
firstCords[1] = getPosition( arr, (*pairs)[i][0] )[1];
這是我想出的唯一可行的解決方案。 我真的很想知道一種方法,如何一線實現呢?
cords
是局部變量,因此在已定義函數的末尾使用它是未定義的行為 。
一種簡單的方法是將指向firstCords
的指針firstCords
給getPosition
然后讓getPosition
填充它。聲明getPosition
像這樣:
void getPosition(int cords[2], char arr[][5], char letter);
然后像這樣scrambling
:
getPosition(firstCords, arr, (*pairs)[i][0]);
注意 int cords[2]
作為getPosition
的形式參數不是數組,而是指針 。
這是Linus Torvalds在Linux Kernel Mailing List上的一篇不錯的文章(取決於您如何定義),其中提到了一些犯了類似錯誤的程序員。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.