210 likes | 633 Views
Dynamic memory allocation in C and C++. 程式設計 潘仁義 CCU COMM. Pointers. void main () { int num = 3; int *nump = # …. Dynamic memory allocation in C (1/3). void some_function () { int *nump; char *letp; planet_t *planetp; …. Dynamic memory allocation in C (2/3).
E N D
Dynamic memory allocationin C and C++ 程式設計 潘仁義 CCU COMM
Pointers • void main () {int num = 3;int *nump = #…..
Dynamic memory allocation in C (1/3) • void some_function () { int *nump;char *letp;planet_t *planetp;…
Dynamic memory allocation in C (2/3) • void some_function () { int *nump; char *letp; planet_t *planetp; … • #include <stdlib.h> • nump=(int*) malloc(sizeof(int)); letp = (char*) malloc(sizeof(char)); planetp = (planet_t *) malloc(sizeof(planet_t));
Dynamic memory allocation in C (3/3) • void some_function () { int *nump; char *letp; planet_t *planetp; … • nump=(int*) malloc(sizeof(int)); letp = (char*) malloc(sizeof(char)); planetp = (planet_t *) malloc(sizeof(planet_t)); • *nump = 307; *letp = ‘Q’; *planetp = blank_planet;
Returning cells to the Heap • …free(letp); free(nump);free(planetp);…free(string1);free(array_of_nums);free(array_of_planets); • double *xp, *xcopyp;xp =(double *)malloc(sizeof(double));*xp = 49.5;xcopy = xp;free(xp); • 『*xcopy』should not be used after it freed or errors can result
Dynamic memory allocation in C++ • int *nump;char *letp;planet_t *planetp;char *string1;int *array_of_nums;planet_t *array_of_planets; • nump= new int;letp = new char;planetp = new planet_t;string1 = new char[str_size];array_of_nums = new int[num_nums];array_of_planets = new planet_t[num_planets]; • delete nump;delete letp;delete planetp;delete [ ] string1;delete [ ] array_of_nums;delete [ ] array_of_planets;
Linked listStructures with pointer components • typedef struct node_s { char current[3]; int volts; struct node_s *linkp;} node_t; • node_t *n1_p, *n2_p, *n3_p;n1_p = (node_t *)malloc(sizeof(node_t));n1_p->volts = 115;n2_p = (node_t *)malloc(sizeof(node_t));n2_p->volts = 12;n3_p = n2_p; /* 令n3_p指向n2_p所指的地方 */
Linking Two Nodes • n1_p->linkp = n2_p; /* 令上面的linkp 指向下面 */ 可用n2_p->voltsn3_p->volts或n1_p->linkp->volts
Three-Node Linked List • n2_p->linkp = (node_t *) malloc(sizeof(node_t));n2_p->linkp->volts=220;strcpy(n2_p->linkp->current, “AC”); • n2_p->linkp->linkp = NULL;
Linked list operations • After an Insertion • After a Deletion
Common programming error • var->component • is valid only if var is of a pointer-to-structure • The most common error is • an attempt to follow a NULL pointer • Checking before access • Do not attempt to reference a node after freeing it