Sunday, June 28, 2009

Initialising arrays

Conside the 2D arrays:  int anArray1[2][3] = {7}; int anArray2[3][5] = { { 1, 2, 3, 4, 5, }, // row 0 { 6, 7, 8, 9, 10, }, // row 1 { 11, 12, 13, 14, 15 } // row 2 }; int anArray3[][5] = { { 1, 2, 3, 4, 5, }, { 6, 7, 8, 9, 10, }, { 11, 12, 13, 14, 15 } }; This won't work int anArray[][] = {{ 1, 2, 3, 4 },{ 5, 6, 7, 8 }}; Initialising pointer to Arrays    /* month_name:  return name of n-th month */    char *month_name(int n)    {        static char *name[] = {           ...

Saturday, June 27, 2009

Dynamic memory allocation

We will talk of calloc, malloc, free and realloc. To use the four functions discussed in this section, you must include the stdlib.h header file. Malloc and Free #include #include /* required for the malloc and free functions */ int main() { int number; int *ptr; int i; printf("How many ints would you like store? "); scanf("%d", &number); ptr = malloc(number*sizeof(int)); /* allocate memory */ if(ptr!=NULL) { for(i=0 ; i *(ptr+i) = i; } for(i=number ; i>0 ; i--) { printf("%d\n", *(ptr+(i-1)));...

Multi-dimensional arrays

#include#includeint main() { int a[3][3][3][3]; //it gives address of a[0][0][0][0] . printf(" \n address of array a is %u", a); printf("\n address of a[2][0][0][0] is %u , " "given by a[2] , %u given by a+2", a[2], a + 2); printf("\n address of a[2][2][0][0] is %u , " "given by a[2][2] , %u given by a[2]+2", a[2][2], a[2] + 2); printf("\n address of a[2][2][1][0] is %u , " "given by a[2][2][1] , %u given by a[2][2]+1", ...