公告版位

目前分類:C,C++ (2)

瀏覽方式: 標題列表 簡短摘要

今日再練習LinkList資料結構時,看到了malloc()函式就研究一下

current = (LNode *)malloc(sizeof(LNode));

//動態配置一LNode結構記憶體大小(Byte)並告知其為LNode的指標型態,把記憶體位置記錄在Current

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

typedef struct LNode
{
 int data;
 struct LNode * rightNode;        
} LNode;

int main(int argc, char *argv[])
{
  int NewNumber,numIndex ;
  LNode * head=NULL;
  LNode * current=NULL;
  LNode * prev =NULL;
  
  printf("sizeof(LNode *)=%dbyte \n",sizeof(LNode *));
  printf("sizeof(LNode)=%dbyte \n",sizeof(LNode));
  
  while(1)
  {
   printf("請輸入串列資料=");
   scanf("%d",&NewNumber);

   if (NewNumber==-1)
   break;
   current = (LNode *)malloc(sizeof(LNode));
   assert(current!=NULL);
    
   current->rightNode=NULL;
   current->data=NewNumber; 
   
   if(head==NULL)
   {head = current;}
   else
   {prev->rightNode=current;}
   
   prev=current;
    
  }  
  current=head;
  numIndex=0;
  while(current !=NULL)
  {      
     printf("LinkedList  NO=%d ,data=%d, MM=%i \n",++numIndex,current->data,current);
     /*用了多次 new / malloc 來做記憶體配置。
       在這種狀況下,不能保證這幾次 allocate 到的記憶體會是連續的*/
     current=current->rightNode;
  }
  current =head;
  while(current !=NULL)
  {
    prev=current;
    current =current->rightNode;
    free(prev);      
  }  
  
  
  system("PAUSE");      
  return 0;
}

重點一:syntax:void * malloc(size_t size);
輸入參數: 所需記憶體大小,以byte來計算。

李山姆's Blog 發表在 痞客邦 留言(0) 人氣()

複習資料結構時,遇到一個C語言宣告如下:

typedef struct CSNode{
   TElemType data;
   struct CSNode *firstchild,*rightsib;
}MyNode , CSTree;

所以就搜尋了一下這要怎麼解釋呢??

首先,先來分析  

1.typedef 的用法

//  定義一個已知資料型態的別名,也就是說可以用這個名稱代替設定的資料型態 

李山姆's Blog 發表在 痞客邦 留言(0) 人氣()