结构体的而指针属性不能直接做左值
作者:互联网
#include<bits/stdc++.h> using namespace std; struct ListNode { int val; ListNode *next =NULL; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {} }; int main() { int a[] = {1,2,3}; ListNode* l = new ListNode(a[0]); cout<<"l->val:"<<l->val<<endl; ListNode *pnew; for (int i = 1; i <3; i++) { pnew = new ListNode(a[i], NULL); l->next = pnew;// l = pnew; //将tmp指 cout<<"l->val:"<<l->val<<endl; } }
#include<bits/stdc++.h> using namespace std; struct ListNode { int val; ListNode *next =NULL; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {} }; int main() { int a[] = {1,2,3}; ListNode* l = new ListNode(a[0],NULL); ListNode *ptemp = l,*pnew; cout<<"l->val:"<<ptemp->val<<endl; for (int i = 1; i <3; i++) { pnew= new ListNode(a[i], NULL); ptemp->next = pnew;//pnew是必须的l->next不能直接做左值,可能是因为l->next不存在未分配空间 ptemp =ptemp->next; //将tmp指 cout<<"l->val:"<<ptemp->val<<endl; } /* 这种写法随着新元素插入,l不断指向下一个,即只能遍历这一便, * 结束后链表就丢失了,此时l指向最后一个元素的下一个元素即null * for (int i = 1; i <3; i++) { l->next = new ListNode(a[i], NULL); l =l->next; cout<<"l->val:"<<l->val<<endl; }*/ ListNode *pn; pn = l; for (int i = 0; i <3; i++) { cout<<"pn->val:"<<pn->val<<endl; pn= pn->next; } }
标签:ListNode,val,int,左值,pnew,next,coutval,指针,属性 来源: https://www.cnblogs.com/q1231/p/16170391.html