============================MODULEZ======================================== | | | The program examples' source codes have been arranged in the same | | order that appeared in the Tutorial. This is unedited and unverified | | compilation. Published as is basis for educational, reacretional and | | brain teaser purposes. All trademarks, copyrights and IPs, wherever | | exist, are the sole property of their respective owner and/or | | holder. Any damage or loss by using the materials presented in this | | tutorial is USER responsibility. Part or full distribution, | | reproduction and modification is granted to any body. | | Copyright 2003-2005 © Tenouk, Inc. All rights reserved. | | Distributed through http://www.tenouk.com | | | | | =========================================================================== Originally programs compiled using Borland C++. Examples compiled using VC++/VC++ .Net and gcc or g++ are given at the end of every Module. For example if you want to compile C++ codes using VC++/VC++ .Net, change the header file accordingly. Just need some modification for the header files...: ------------------------------------------------- #include //for system() #include ... { C++ codes... } ------------------------------------------------- should be changed to: ------------------------------------------------- #include //use C++ wrapper to call C functions from C++ programs... #include using namespace std; ... { C++ codes... } ------------------------------------------------- In VC++/VC++ .Net the iostream.h (header with .h) is not valid anymore. It should be C++ header, so that it comply to the standard. In older Borland C++ compiler this still works, but not proper any more... and for standard C/C++ the portability should be no problem or better you read Module23 at http://www.tenouk.com/Module23.html to get the big picture...For C codes, they still C codes :o) ========================================================================= =======================JUST C Codes HERE================================= /*storage class and scope*/ #include void funct1(void); void funct2(void); /*external variable, scope is global to main(), funct1() and funct2(), extern keyword is omitted here, coz just one file*/ int globvar = 10; int main() { printf("\n****storage classes and scope****\n"); /*external variable*/ globvar = 20; printf("\nVariable globvar, in main() = %d\n", globvar); funct1(); printf("\nVariable globvar, in main() = %d\n", globvar); funct2(); printf("\nVariable globvar, in main() = %d\n", globvar); return 0; } /*external variable, scope is global to funct1() and funct2()*/ int globvar2 = 30; void funct1(void) { /*auto variable, scope local to funct1() and funct1() cannot access the external globvar*/ char globvar; /*local variable to funct1()*/ globvar = 'A'; /*external variable*/ globvar2 = 40; printf("\nIn funct1(), globvar = %c and globvar2 = %d\n", globvar, globvar2); } void funct2(void) { /*auto variable, scope local to funct2(), and funct2() cannot access the external globvar2*/ double globvar2; /*external variable*/ globvar = 50; /*auto local variable to funct2()*/ globvar2 = 1.234; printf("\nIn funct2(), globvar = %d and globvar2 = %.4f\n", globvar, globvar2); } -------------------------------------------------------------------------------------------- /*static storage class program example*/ #include #define MAXNUM 3 void sum_up(void); int main() { int count; printf("\n*****static storage*****\n"); printf("Key in 3 numbers to be summed "); for(count = 0; count < MAXNUM; count++) sum_up(); printf("\n*****COMPLETED*****\n"); return 0; } void sum_up(void) { /*At compile time, sum is initialized to 0*/ static int sum = 0; int num; printf("\nEnter a number: "); scanf("%d", &num); sum += num; printf("\nThe current total is: %d\n", sum); } -------------------------------------------------------------------------------------------- #include int a(); int b(); int c(); int a() { b(); c(); return 0; } int b() { return 0; } int c() { return 0; } int main() { a(); return 0; } -------------------------------------------------------------------------------------------- /*Playing with malloc(), memory on the heap*/ #include #include void main() { int x; int *y; /*do 100000 times iteration, 100000 blocks*/ for(x=0; x<100000; x++) { /*For every iteration/block, allocate 16K, system will truncate to the nearest value*/ y = (int *)malloc(16384); /*If no more memory*/ if(y == NULL) { puts("No more memory lol!"); /*exit peacefully*/ exit(0); } /*Allocate the memory block, print the block and the address*/ printf("Allocating-->block: %i address: %p\n", x, y); } /*Here, we do not free up the allocation*/ } -------------------------------------------------------------------------------------------- /*Playing with free(), memory on the heap*/ #include #include void main() { int x; int *y; int *buffer = NULL; /*do 100 times iteration, 100 blocks*/ for(x=0; x<100; x++) { /*For every iteration/block, allocate 16K, system will truncate to the nearest value*/ y = (int *)malloc(16384); /*If there is a problem*/ if(y == NULL) { puts("No more memory for allocation lol!"); /*exit peacefully*/ exit(0); } /*Allocate the memory block, print the block and the address*/ printf("Allocating-->block: %i address: %p\n", x, y); printf("---->Freeing the memory block: %i address: %p\n", x, y); free((void *)buffer); } } -------------------------------------------------------------------------------------------- /*malloc() and struct*/ #include #include struct record{ char name[15]; int age; int id_num; }; int main() { struct record *ptr; printf("\n--malloc() & struct--\n"); ptr = (struct record *)malloc((sizeof(struct record))); if(ptr) { printf("\nStudent Name: "); gets(ptr->name); printf("Student Age: "); scanf("%d", &ptr->age); printf("Student Id: "); scanf("%d", &ptr->id_num); printf("\nStudent Name: %s", ptr->name); printf("\nStudent Age: %d", ptr->age); printf("\nStudent Id Number: %d\n", ptr->id_num); free(ptr); } else printf("\nMemory allocation fails!!!\n"); return 0; } -------------------------------------------------------------------------------------------- /*Playing with malloc() and calloc()*/ #include #include #define END 10 int main() { int *ptr1, *ptr2, *ptr3; int i; /*Get memory for an array using malloc() - 1 parameter*/ ptr1 = (int *) malloc(END*sizeof(int)); /*If memory allocation fails...*/ if (ptr1 == NULL) { fprintf(stderr, "malloc() failed!\n"); /*exit with an error message*/ exit(1); } /*Initialize the array using array notation*/ for(i = 0; i < END; i++) { ptr1[i] = i+i; } /*********************************************************/ /*Getting memory for an array using calloc() - 2 parameters*/ ptr2 = (int *) calloc(END, sizeof(int)); /*If memory allocation fails...*/ if(ptr2 == NULL) { fprintf(stderr, "calloc() failed!\n"); /*exit with an error message*/ exit(1); } /*Initialize the array using pointer arithmetic*/ ptr3 = ptr2; for(i = 0; i < END; i++) { *(ptr3++) = i+i; } /*Print array contents*/ printf("---Using malloc()---\n"); printf("Array pointed by ptr1:\n"); for(i = 0; i < END; i++) { printf("%3d ", ptr1[i]); } printf("\n\n"); printf("---Using calloc()---\n"); printf("Array pointed by ptr2:\n"); for(i = 0; i < END; i++) { printf("%3d ", ptr2[i]); } printf("\n\n"); return 0; } -------------------------------------------------------------------------------------------- /*calloc() and malloc() example*/ #include #include #define n 10 /*a struct*/ typedef struct book_type { int id; char name[20]; float price; }book; int main(void) { int *aPtr = NULL, *bPtr = NULL, m = 0; char *str = NULL; book *bookPtr = NULL; /*create an int array of size 10*/ aPtr = (int *)calloc(n, sizeof(int)); /*do some verification*/ if(aPtr == NULL) { printf("calloc for integer fails lol!\n"); exit (0); } else printf("memory allocation for int through calloc() is OK\n"); /*create a char array of size 10*/ str = (char *)calloc(n, sizeof(char)); if(str == NULL) { printf("calloc for char fails lol!\n"); exit (0); } else printf("memory allocation for char through calloc() is OK\n"); /*create a structure of book*/ bookPtr = (book *)malloc(sizeof(book)); if(bookPtr == NULL) { printf("malloc for struct fails lol!\n"); exit (0); } else printf("memory allocation for struct through malloc() is OK\n"); /*clean up the memory allocated*/ free(aPtr); free(str); free(bookPtr); /*other way*/ /*get the number of elements from the user and then allocate*/ printf("\nEnter the size of integer array (bytes): "); scanf("%d", &m); bPtr = (int *)calloc(m, sizeof(int)); if(bPtr == NULL) { printf("calloc for int fails lol!\n"); exit (0); } else printf("memory allocation for int through calloc() is OK\n"); free(bPtr); return 0; } -------------------------------------------------------------------------------------------- /*Playing with realloc(). Store user input in an array*/ #include #include #define INITIAL_SIZE 5; int main() { int *Arr, *temp; int limit, input, n = 0, r, i; /*Initially, allocate some space for A*/ limit = INITIAL_SIZE; Arr = (int *) malloc (limit * sizeof(int)); /*Do some verification, if fail*/ if (Arr == NULL) { /*Display the error message*/ fprintf(stderr, "malloc() failed!\n"); /*Exit with the error code*/ exit(1); } /*array loop*/ printf("Enter numbers, 1 per line. End with ctrl-D\n"); while(1) { printf("Next number: "); r = scanf("%d", &input); fflush(stdin); /*verify the input*/ if(r < 1) break; /*Get more space for Arr using realloc()*/ if(n >= limit) { printf("More than 5 elements per loop, reallocating the storage... \n"); limit = 2 * limit; temp = (int *)realloc(Arr, limit * sizeof(int)); /*Verify again...*/ if(temp == NULL) { fprintf(stderr, "realloc() failed!\n"); exit(1); } else printf("realloc is OK lol, proceed your input...\n"); Arr = temp; } Arr[n] = input; n++; } /*Trim Arr down to size*/ temp = (int *)realloc(Arr, n*sizeof(int)); /*Verify...*/ if(temp == NULL) { fprintf(stderr, "realloc() fails lol!\n"); exit(1); } Arr = temp; printf("\nContents of the array Arr:\n"); /*Print the array*/ for(i = 0; i < n; i++) { printf("%2d ", Arr[i]); } printf("\n"); return 0; } -----------------------------------------GCC--------------------------------------------------- /*calloc() and malloc() example*/ #include #include #define n 10 /*a struct*/ typedef struct book_type { int id; char name[20]; float price; }book; int main(void) { int *aPtr = NULL, *bPtr = NULL, m = 0; char *str = NULL; book *bookPtr = NULL; /*create an int array of size 10*/ aPtr = (int *)calloc(n, sizeof(int)); /*do some verification*/ if(aPtr == NULL) { printf("calloc for integer fails lol!\n"); exit (0); } else printf("memory allocation for int through calloc() is OK\n"); /*create a char array of size 10*/ str = (char *)calloc(n, sizeof(char)); if(str == NULL) { printf("calloc for char fails lol!\n"); exit (0); } else printf("memory allocation for char through calloc() is OK\n"); /*create a structure of book*/ bookPtr = (book *)malloc(sizeof(book)); if(bookPtr == NULL) { printf("malloc for struct fails lol!\n"); exit (0); } else printf("memory allocation for struct through malloc() is OK\n"); /*clean up the memory allocated*/ free(aPtr); free(str); free(bookPtr); /*other way*/ /*get the number of elements from the user and then allocate*/ printf("\nEnter the size of integer array (bytes): "); scanf("%d", &m); bPtr = (int *)calloc(m, sizeof(int)); if(bPtr == NULL) { printf("calloc for int fails lol!\n"); exit (0); } else printf("memory allocation for int through calloc() is OK\n"); free(bPtr); return 0; } -------------------------------------------------------------------------------------------- /****************malalloc.c***************************/ /************run on FeDora 3 Machine*********************/ /*Playing with malloc() and free(), memory on the heap*/ #include #include int main() { int x; int *y; int *buffer = NULL; /*do 100 times iteration, 100 blocks*/ for(x=0; x<100; x++) { /*For every iteration/block, allocate 16K, system will truncate to the nearest value*/ y = (int *)malloc(16384); /*If there is a problem*/ if(y == NULL) { puts("No more memory for allocation lol!"); /*exit peacefully*/ exit(0); } else { /*Allocate the memory block, print the block and the address*/ printf("Allocating-->block: %i address: %p\n", x, y); free((void *)buffer); printf("---->Freeing the memory block: %i address: %p\n", x, y); } } return 0; } =======================================================================================================