C++ for循环中的局部变量地址
为了方便刷题,我想写一个根据vector自动按顺序生成链表的函数,在写的过程中发现了一个值得注意的地方
猜猜tempNode这个变量在每次循环中的地址变不变
template<class T>
ListNode* createListNode(vector<T> data)
{
ListNode* head;
head = new ListNode(data[0]);
ListNode* tempPtr;
tempPtr = head;
for (int i = 1; i < data.size(); ++i)
{
ListNode tempNode(data[i]);
tempPtr->next = &tempNode;
tempPtr = tempPtr->next;
}
return head;
}
思路就不说了,很简单,但这里会有问题
运行tempPtr->next = &tempNode;
前
tempPtr还是表头的地址,没有错
运行tempPtr->next = &tempNode;
后
tempPtr指向了下一个节点的地址,也没有错
到了下一次循环,问题就来了
因为这种写法在循环里每次初始化变量的时候,地址是不会变的,所以会出现什么问题自己可以想象出来
正确的写法
template<class T>
ListNode* createListNode(vector<T> data)
{
ListNode* head;
head = new ListNode(data[0]);
ListNode* tempPtr;
tempPtr = head;
for (int i = 1; i < data.size(); ++i)
{
ListNode* tempNode;
tempNode = new ListNode(data[i]);
tempPtr->next = tempNode;
tempPtr = tempPtr->next;
}
return head;
}
实际上能用for_each的话更好,但是我这里会出现莫名其妙的错误,提示for_each是未定义的标识符,后边再解决这个问题