C language to create a linked list error through the pointer parameter application dynamic memory instance analysis

  • 2020-04-02 02:45:50
  • OfStack

The example of this article describes the C language to create a linked list of classic errors through the pointer parameter application dynamic memory, Shared with you for your reference. Specific examples are as follows:


#include <stdio.h>
#include <stdlib.h>//To include this header file with malloc

typedef struct node
{
  int data;
  struct node* next;//Notice the rules for defining structural variables here
} Node;

void createLinklist(Node* pHder, int length)
{
  int i = 0;
  Node* pTail = NULL;
  Node* pTemp = NULL;
  printf("createn");

  for (i = 0; i < length; i++)
  {
    pTemp = (Node*)malloc(sizeof(Node));//Originally thought the mistake in this place, the original is a misunderstanding
    
    pTemp->data = i*10;
    pTemp->next = NULL;
    if (NULL == pHder)
    {
      pHder = pTemp;//The wrong key
    }
    else
    {
      pTail->next = pTemp;
    }
    pTail = pTemp;
  }
}

void print(Node* pHeader)
{
  Node* p = pHeader;
  printf("printn ");
  while(p)
  {
    printf("%4d ", p->data);
    p = p->next;
  }
  putchar('n');
}

int main(void)
{
  Node* pHeader = NULL;//NULL macros (all uppercase) are used in C and C++ to determine whether a pointer is NULL
  createLinklist(pHeader, 10);//This is a classic mistake, and that's why it's wrong
  
  
  
  
  
  
  
  print(pHeader);

  return 0;
}

The above examples are analyzed in detail in the form of annotation, which is not difficult to understand. It is hoped that this article will be helpful to the study of C program data structure and algorithm design.


Related articles: