我有一个名为 SensorNode 的类,其中包含(除其他外)传感器对象的链接列表。节点有一个数据成员表示它剩余的电池电量,每个传感器都有一个数据成员表示它们消耗了多少电量。我有一个名为 processTimeClick 的函数,它应该遍历节点中传感器的整个链接列表,并从节点剩余的电池中减去它们使用的电量。不幸的是,我收到“错误,错误的访问代码”,我不知道为什么。这是我的功能,我希望有人能看到我的逻辑哪里错了。
void SensorNode::processTimeClick() {
if (batt == 0) {
}
else {
temp = mySensors;
do {
if (batt <=0) {
cout << "\nThis node has run out of battery\n";
func = 0;
break;
}
batt = (batt - (temp->SensEl->getPC()));
temp = temp->LLelement;
} while (temp->LLelement != NULL); //My code stops here and says "Thread 1:EXC_BAD_ACCESS (code=1, address=0x0)
}
}
为了更容易理解: temp 和 mySensors 都是“SensorBlock”类型(即链表对象)的指针(在 SensorNode 类中声明)。 batt 是 SnesorNode 类中的 float 数据成员。
这是 SensorBlock 类的声明:
class SensorBlock {
friend class SensorNode;
SensorBlock * LLelement;
sensor * SensEl;
SensorBlock(sensor* senspoint);
};
SensorBlock::SensorBlock(sensor* senspoint) {
SensEl = senspoint;
LLelement = NULL;
}
感谢您的帮助!
最佳答案
我想你希望你的循环看起来更像这样:
while (temp) {
if (batt <=0) {
cout << "\nThis node has run out of battery\n";
func = 0;
break;
}
batt = (batt - (temp->SensEl->getPC()));
temp = temp->LLelement;
}
这样,在您尝试使用 temp
之前检查它以确保它不为空。
如果你有这样一个循环:
do {
// use temp
temp = temp->LLelement;
} while (temp->LLelement);
相当于
beginning_of_loop:
// use temp -- oops it might be null!
temp = temp->LLelement;
// temp might be null here
if (temp->LLelement) goto beginning_of_loop;
如果将 while 放在顶部,则相当于:
beginning_of_loop:
if (!temp) goto end_of_loop:
// use temp -- can't be null
temp = temp->LLelement;
// temp might be null here, but we aren't using it
goto beginning_of_loop;
end_of_loop:
关于c++ - 如何循环链表以减少值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17013249/