下面一段c++程序
int i = 5;
cout << "dui_apply:" << endl;
while (--i){
int *dui_apply = new int;
cout << dui_apply << endl;
}
cout <<endl<< "stack_init:" << endl;
i = 5;
while (--i){
int stack_init = 1;
cout << &stack_init << endl;
}
程序输出:
dui_apply:
030454D8
0304A6C0
0304E928
0304E968
stack_init:
00DCF744
00DCF744
00DCF744
00DCF744
使用int a=1这种方式编译器是在程序运行前已经在栈中分配好一个int型名叫a的变量,无论int a=1;是否在循环内部,在数据栈中a一直都是那个地址对应的a,不会英文int a=1执行的多次就会占用多个不同的内存,这点其实很容易理解。
但是,这样一个简单的问题,在做复制一个链表这个程序时,就栽了跟头,在循环复制链表时,需要申请新的链表节点,而本人却想当然的用了:
ListNode temp=ListNode();
申请一个新的节点,可笑啊!正确的做法当时是临时申请内存:
point=new ListNode();
下面复制链表部分程序比较
//错误的程序,RandomListNode temp=RandomListNode(0);这种方式创建新节点显然错误
while (node->next != nullptr){
//当前节点值为node的值
np->label = node->label;
//跳到下一个node,准备复制
node = node->next;
//新建一个新节点,错误的新建节点
RandomListNode temp=RandomListNode(0);
//q=new RandomListNode(0);
//cout << &temp << endl;
//新节点的值为node的值
temp.label = node->label;
//当前节点的下一个节点为新节点
np->next = &temp;
//当前节点指针指向新节点
np = &temp;
}
//正确的做法,q=new RandomListNode(0);临时申请内存,堆中
while (node->next != nullptr){
np->label = node->label;
node = node->next;
q=new RandomListNode(0);
q->label = node->label;
np->next = q;
q->next = nullptr;
np = q;
}