This article describes the C language to create a linked list of the classic error in the application of the pointer parameters of dynamic memory, shared for everyone to reference. The specific example is as follows:
#include <stdio.h> #include <stdlib.h>//with malloc to include this header file typedef struct Node {int data;
struct node* next;//This place attention to the definition rules of struct variables node;
void Createlinklist (node* phder, int length) {int i = 0;
node* ptail = NULL;
node* ptemp = NULL;
printf ("create\n"); for (i = 0; i < length; i++) {ptemp = (node*) malloc (sizeof (Node));/I thought it was wrong in this place, the original is misunderstood/* This sentence is for the ptemp to assign value, the
In the for inside and for the outside definition ptemp is indifferent to the * * Ptemp->data = i*10;
Ptemp->next = NULL;
if (NULL = = Phder) {Phder = ptemp;//error Key} else {ptail->next = ptemp;
} ptail = ptemp;
} void Print (node* pheader) {node* p = pheader;
printf ("print\n");
while (p) {printf ("%4d", p->data);
p = p->next;
} putchar (' \ n ');
int main (void) {node* pheader = null;//C and C + + the judgment pointer is null with NULL macros (all caps) createlinklist (Pheader, 10);//This is a typical mistake, and the reason for the mistake is right here. /* Pheader is a node* variable////* Since it is a variable, the compiler must make a temporary copy of the variable when passing the parameter. * * Suppose this temporary copy is _Pheader_ * * * When just passed in, Pheader and _pheader_ are the same * * * but after dynamically requesting memory, _pheader_ points to the new address [[note]] It is not modifying the value of the content that the _pheader_ points to, but modifying _
Pheader_ point to the address * * And at this point the Pheader still point to the original address * * * * So, in fact, in createlinklist the entire operation of the Pheader has not been affected by the effect of * * print (Pheader);
return 0;
}
The above example makes a detailed analysis of the error points in the form of annotations, I believe it is easy to understand. I hope this article is helpful to the study of C program data structure and algorithm design.