new ListElem(...); |
|
|
|
|
Illustrated usage:
|
#include <stdio.h> #include <stdlib.h> // Contains the declaration of malloc() /* ------------------------ Structure definition ------------------------ */ struct BankAccount { int accNum; double balance; }; int main(int argc, char *argv[]) { struct BankAccount* p; p = malloc( 16 ); // Create one BankAccount struct variable (*p).accNum = 123; // Long form to access a member variable p->balance= 400; // Short form to access a member variable printf("p->accNum = %d p->balance = %f\n", p->accNum, p->balance); } |
How to run the program:
|
|
#include <stdlib.h> // You must include this header file // to obtain the function declaration free( memoryAddress ); Effect: unreserve (de-allocate) the previously allocated memory block that starts at memoryAddress |
Iluustrated:
|
|
#include <stdio.h> #include <stdlib.h> /* ------------------------ Structure definition ------------------------ */ struct BankAccount { int accNum; double balance; }; int main(int argc, char *argv[]) { struct BankAccount* p; p = malloc( sizeof(struct BankAccount) ); // (1) (*p).accNum = 123; // Long form to access a member variable p->balance= 400; // Short form to access a member variable printf("p->accNum = %d p->balance = %f\n", p->accNum, p->balance); /* ================================================== Unreserve memory that was allocated at step (1) ================================================== */ free(p); } |
How to run the program:
|
#include <stdio.h> // NULL is defined inside this header file head = NULL; |
|
#include <stdio.h> #include <stdlib.h> /* ------------------------ List element definition ------------------------ */ struct ListElem { int value; struct ListElem* next; }; int main(int argc, char *argv[]) { struct ListElem* head; // Head of list struct ListElem* p; // Help variable to allocate new list element head = NULL; // Empty list /* ======================================================== Insert at head technique: 1. create new list element p put values in the payload area... 2. make p point to first element in list 3. make head point to new list element ======================================================== */ p = malloc( sizeof(struct ListElem) ); // (1) p->value = 123; // Payload... p->next = head; // (2) head = p; // (3) } |
How to run the program:
|
p = head; // Start at first element while ( p != NULL ) { /* ------------------------------------ Put code here to do something with the list element (*p) E.g.: (*p).value = ... or p->value = .... ------------------------------------- */ p = p->next // Visit next element in list } |
void printList( struct ListElem* h ) { while ( h != NULL ) { printf(" %d\n", h->value ); // Print h = h->next; // Go to next element in list } printf("\n"); } |
How to run the program:
|