【发布时间】:2019-03-18 16:04:59
【问题描述】:
我编写的用于初始化 2D 网格以实现康威生命游戏的函数存在一些问题。此函数 initialize(bool*, int, int) 使用指针算法来访问我要传递其指针的二维数组中的所有值。
main.cpp
#include "logic.cpp"
#include <SFML/Graphics.hpp>
using namespace std;
const unsigned int WIDTH = 640;
const unsigned int HEIGHT = 640;
const int RESOLUTION = 10;
const int rows = (WIDTH/RESOLUTION) - 1;
const int cols = (HEIGHT/RESOLUTION) - 1;
int main()
{
bool curr_gen[rows][cols];
bool next_gen[rows][cols];
bool* curr = &curr_gen[0][0];
bool* next = &next_gen[0][0];
initialize(curr, rows, cols);
/*sf::RenderWindow window(sf::VideoMode(WIDTH, HEIGHT), "Conway's Game of Life");
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
window.display();
}*/
return 0;
}
逻辑.cpp
#include <iostream>
#include <ctime>
void initialize(bool* p, int r, int c)
{
srand(time(NULL));
for(int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
{
if(rand()% 2)
*(*(p+i)+j) = true;
else
*(*(p+i)+j) = false;
}
}
}
我得到的所有错误都说一元'*'的无效类型参数(有'int')。在我看来, (*(p+i)+j) 给出了一个二维数组元素的地址 (&arr[i][j]),并且在取消引用时,我可以访问 arr[i][j] 和更改。如果有人能指出我推理中的错误,我将不胜感激。我在 Code::Blocks 中使用 GNU GCC 编译器。
【问题讨论】:
标签: c++ arrays pointers pass-by-reference