BUG: Today I wrote a very SB code, the problem actually I have noticed, in the previous writing such code, I also left a mind, but may be a long time not to write these things lead to new problems arising. In fact, I have written a note about this problem before, and now write a deeper impression. The code is first attached:
#ifndef LIST_INSERTREMOVEPRINT_H
#define LIST_INSERTREMOVEPRINT_H
#include<iostream>
struct ListNode{
int val;
struct ListNode *nxt;
};
void addListNode(struct ListNode*list,int value){
struct ListNode *nodeInsert=(struct ListNode*)(malloc(sizeof(struct ListNode)));
nodeInsert->val=value;
nodeInsert->nxt=NULL;
if(list==NULL){
list=nodeInsert;
return ;
}
struct ListNode *iter=list;
while(iter->nxt!=NULL){
iter=iter->nxt;
}
iter->nxt=nodeInsert;
}
#end
In fact, a familiar person will know where the problem is at a glance!!!!! The highlight section illustrates the problem. The reason for making this mistake is that the passing of the pointer is not very clear.
void addListNode(struct ListNode*list,int value)
There are two parameters in this function, one is the pointer type of the linked list node, and the other one is the int type. For this list node pointer, what are we passing in? Of course, the incoming is an address, because it is a pointer. Well, how do we pass this pointer, the value of!!!!!!!. You pass the address or the value of Ah, but this value is "address" and so on. Now that you understand this, the problem is, you change it in the function body.
list=nodeInsert
What do you mean by this? ,,, to pay the list for this Nodeinsert address? That is, you have this function.
void test(int a,int value){
int c;
a=c;
}
What do you mean? Do you really want to change the argument value by A=c in the function body? Get the hell out of here.
iter->nxt=nodeInsert;
This is even more ridiculous, you are still changing the value of the parameter, this must not be.
How to fix this bug1, if you want to change the argument through the parameter, for the address of the value of the problem, you can use "*"-----dereference operator.
That is , we use this solution to refer to this parameter, so that we find the corresponding space of the formal parameter address, in memory to change the value of this real. 2, the pointer to the pointer, and then the dereference operator. The argument can be changed by the parameter!!!!!!, because it has to be dereferenced.
From for notes (Wiz)
Insert problem with linked list