【发布时间】:2017-07-10 20:17:00
【问题描述】:
我的问题是,当尝试添加到数组中的链表时,它似乎不起作用,我几乎完全不知道为什么会这样。首先我声明对象move,如下所示:
struct move {
move(int startX, int startY, int endX, int endY)
{
this->startX = startX;
this->startY = startY;
this->endX = endX;
this->endY = endY;
this->next = nullptr;
}
move()
{
next = nullptr;
this->startX = -1;
}
int startX;
int startY;
int endX;
int endY;
move* next;
};
然后我声明 2 个数组,一个包含 100 个 moveobject 的链表,另一个包含指向第一个数组中每个链表中元素的指针。如下图:
move possibleMoves[100];
move * endOfLists[100];
然后我初始化这些数组,如下所示:
for (int i = 0; i < 100; i++) {
possibleMoves[i] = move();
endOfLists[i] = &possibleMoves[i];
}
转到添加到 possibleMoves 数组中的一个链表的函数本身,我将其原型如下:
void listAdd(move * list, move * object, int width);
我这样称呼它:
if (possibleMoves[0].startX == -1) {
possibleMoves[0] = *(new move(x, y, x + xOffset, y + yOffset));
}else {
listAdd(endOfLists[width], new move(x, y, x + xOffset, y + yOffset), width);
}
函数声明如下:
void listAdd(move * list, move * object, int width) {
int count = 0;
while (list->next != nullptr){
count++;
list = (*list).next;
}
std::cout << "\nCount: " << count << std::endl;
list->next = object;
endOfLists[width] = list->next;
}
Count 始终输出为“0”。
这是所有代码(https://pastebin.com/E5g58N6L)的链接,它并不漂亮。 listAdd 过程在第 188、197 和 444 行调用。这是 MCVE:
#include<stdio.h>
#include <stdlib.h>
#include<math.h>
#include<iostream>
struct move {
move(int startX, int startY, int endX, int endY)
{
this->startX = startX;
this->startY = startY;
this->endX = endX;
this->endY = endY;
this->next = nullptr;
}
move()
{
next = nullptr;
this->startX = -1;
}
int startX;
int startY;
int endX;
int endY;
move* next;
};
void listAdd(move * list, move * object, int width);
move possibleMoves[100];
move * endOfLists[100];
int main() {
int x = 0;
int y = 0;
int xOffset = 1;
int yOffset = 1;
int width = 0;
for (int i = 0; i < 100; i++) {
possibleMoves[i] = move();
endOfLists[i] = &possibleMoves[i];
}
if (possibleMoves[0].startX == -1) {
possibleMoves[0] = *(new move(x, y, x + xOffset, y + yOffset));
}else {
listAdd(endOfLists[width], new move(x, y, x + xOffset, y + yOffset), width);
}
void listAdd(move * list, move * object, int width) {
int count = 0;
while (list->next != nullptr)
{
count++;
list = (*list).next; //Go down the list until it reaches an item with nothing next.
}
std::cout << "\nCount: " << count << std::endl;
list->next = object;
endOfLists[width] = list->next;
}
【问题讨论】:
-
仅供参考,初始化循环的第一行
possibleMoves[i] = move();毫无意义。已经为该数组中的所有实例调用了该构造函数。 -
我们只是测试以确保。 (不过感谢您的确认,我们正在质疑我们现在所知道的一切)
-
你能发布你用来调用
listAdd的实际代码吗?你可以写的最短的 main 来测试它。 -
我添加了整个代码的 pastebin,但我已经检查了 'x'、'y'、'yOffset'、'xOffset' 和 'width'。我几乎可以肯定这些参数设置正确。
-
我很确定@kabanus 正在请求MCVE,这可能对您自己发现问题以及帮助任何试图回答您的问题的人有用。
标签: c++ arrays pointers reference linked-list