Context
我使用的struct创建的,GitHub,源码地址
Struct遇到的坑
struct ListNode
{
int m_nValue;
ListNode* m_next;
};
ListNode test1;
cout << "\ntest: " << &test1;
ListNode test2;
cout << "\ntest: " << &test2;
ListNode test3;
cout << "\ntest: " << &test3;
for(int i = 0; i<3; i++) {
ListNode test4;
cout << "\ntest4: " << &test4;
}
输出
test: 0x7ffee2887618
test: 0x7ffee2887608
test: 0x7ffee28875f8
test4: 0x7ffee28875e0
test4: 0x7ffee28875e0
test4: 0x7ffee28875e0
我擦了,和java的差异好大
- ListNode test 居然可以分配内存。。。。
- 但是再循环体内 ?分配的一样的内存
解决方法
ListNode* test4 = new ListNode;
//—2021年11月22日增补
ListNode test 是在方法栈上分配内存 (想像1个桶放了10张饼, 你新增调用1个方法,就放一张饼。栈内存数据就是饼上的芝麻),退出方法,变量就没了。
new 、alloc是在堆上分配,应用关了就没了。
Java虚拟机栈(就是方法调用的栈)的局部变量只能分配:基础变量(int、double、bool),和指向对象的指针,而对象则分配在堆上。
版权声明:本文为zhjali123原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。