c++ - C++ 函数、数组和指针
问题描述
关于这个已经有很多了,但没有一个能解决我的问题,或者我只是不明白答案。我只是想从函数中返回一个数组
此外,我必须将我的所有功能都放在对我来说也很奇怪的主要功能之上。
当我尝试使用指针时会发生以下情况:
int * RookMoves(int startingPosition, bool isWhite, int theBoard[64]){
int startingPositionXY[2] = { startingPosition % 8, (startingPosition - (startingPosition % 8)) / 8 };
int possibleRookPositions[14];
int possiblePosXY[2];
int counter = 0;
for (int h = 0; h < 2; h++)
{
int counter2 = 1;
for (int j = 0; j < 2; j++)
{
counter2 *= -1;
for (int i = 1; i < 8; i++)
{
int other = startingPositionXY[h] + (i * counter2);
int hInverted = (h + abs(h - 1)) * abs(h - 1); // 0 + 1 * 1 = 1 but 1 + 0 * 0 = 0
if (other < 8 && other > -1)
{
possiblePosXY[h] = other;
possiblePosXY[hInverted] = startingPositionXY[hInverted];
int movesOneDim = possiblePosXY[0] + (possiblePosXY[1] * 8);
if (CalculateSameColor(isWhite, theBoard[movesOneDim])) {
possibleRookPositions[counter] = movesOneDim;
counter++;
if (CalculateEnemy(isWhite, theBoard[movesOneDim]))
{
break;
}
}
else
{
break;
}
}
else
{
break;
}
}
}
}
for (int i = counter; i < 14; i++) //simply changing any unused elements to -1 for later recognition
{
possibleRookPositions[i] = -1;
}
cout << sizeof(possibleRookPositions) / sizeof(possibleRookPositions[0]) << ' '; // returns 14 just as it should
return possibleRookPositions;
}
int main()
{
int testBoard[64];
for (int i = 0; i < 64; i++) {
testBoard[i] = 0;
}
int* arr = RookMoves(21, true, testBoard);
cout << sizeof(arr) / sizeof(arr[0]); //ouputs: 1, should be 14
}
网络上说指针 one 应该可以工作,但它没有,它返回一个大小为 1 的数组。
解决方案
C++ 中的数组,在“简单”代码中,要么是 std::vector,要么是 std::array。那些可以毫无问题地退回。我想说您的问题是您主要编写 C 并称其为 C++。恕我直言,C 对初学者来说更难掌握 - 所以请使用 C++ 供您使用的事实!
C 风格的数组当然是任何专业的 C++ 程序员都完全理解的,但是每当我被迫编写这样的代码时(由于相当于客户的要求),它几乎从未在第一次尝试时通过测试。所以不要太担心:即使是可以编写一个编译器来获取这个数组代码并产生汇编输出的人,在某种程度上仍然难以让它正确。它很笨重,在今天的 C++ 中几乎没有位置。
推荐阅读
- php - 重新格式化字符串 PHP 数组中的数字
- node.js - 使用带有 mongodb `connect` 的数据库
- php - 触发按钮单击 Enter
- hyperledger-fabric - Hyperledger Fabric:无法将所有对等方加入通道。原因:TypeError:client.getEventHubsForOrg 不是函数
- tfs - 在进行 TFS 部署时配置多个主机头名称
- reactjs - React.js 中的状态不会立即更新
- machine-learning - 训练模型来识别句子中出现的名字
- javascript - 无法使用 Selenium Webdriver 遍历下拉列表
- calendar - 蓝色棱镜日历
- javascript - 在 Ajax 和 php 中自动下载文件