Unit4 Slides


Published on

I am working as a Assistant Professor in ITS, Ghaziabad. These 'C' language slides are very useful for students of any university.

Published in: Technology, Education
1 Like
  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Unit4 Slides

  1. 1. Arrays: Array notations and representations, manipulating array elements, using multidimensional arrays, arrays of unknown or varying size. Structure : Purpose and usage of structures, declaring structures, assigning of structures. Pointers to Objects : Pointer and address arithmetic, pointer operations and declarations, using pointers as function arguments, Dynamic memory allocation, defining and using stacks and linked lists. UNIT IV
  2. 2. Introduction <ul><li>Arrays </li></ul><ul><ul><li>Structures of related data items </li></ul></ul><ul><ul><li>Static entity – same size throughout program </li></ul></ul>
  3. 3. 6.2 Arrays <ul><li>Array </li></ul><ul><ul><li>Group of consecutive memory locations </li></ul></ul><ul><ul><li>Same name and type </li></ul></ul><ul><li>To refer to an element, specify </li></ul><ul><ul><li>Array name </li></ul></ul><ul><ul><li>Position number </li></ul></ul><ul><li>Format: </li></ul><ul><ul><ul><li>arrayname [ position number ] </li></ul></ul></ul><ul><ul><li>First element at position 0 </li></ul></ul><ul><ul><li>n element array named c : </li></ul></ul><ul><ul><ul><li>c[ 0 ] , c[ 1 ] ... c[ n – 1 ] </li></ul></ul></ul>Name of array (Note that all elements of this array have the same name, c ) Position number of the element within array c c[6] -45 6 0 72 1543 -89 0 62 -3 1 6453 78 c[0] c[1] c[2] c[3] c[11] c[10] c[9] c[8] c[7] c[5] c[4]
  4. 4. 6.2 Arrays <ul><li>Array elements are like normal variables </li></ul><ul><ul><ul><li>c[ 0 ] = 3; </li></ul></ul></ul><ul><ul><ul><li>printf( &quot;%d&quot;, c[ 0 ] ); </li></ul></ul></ul><ul><ul><li>Perform operations in subscript. If x equals 3 </li></ul></ul><ul><ul><ul><li>c[ 5 - 2 ] == c[ 3 ] == c[ x ] </li></ul></ul></ul>
  5. 5. 6.3 Declaring Arrays <ul><li>When declaring arrays, specify </li></ul><ul><ul><li>Name </li></ul></ul><ul><ul><li>Type of array </li></ul></ul><ul><ul><li>Number of elements </li></ul></ul><ul><ul><ul><li>arrayType arrayName[ numberOfElements ]; </li></ul></ul></ul><ul><ul><li>Examples: </li></ul></ul><ul><ul><ul><li>int c[ 10 ]; </li></ul></ul></ul><ul><ul><ul><li>float myArray[ 3284 ]; </li></ul></ul></ul><ul><li>Declaring multiple arrays of same type </li></ul><ul><ul><li>Format similar to regular variables </li></ul></ul><ul><ul><li>Example: </li></ul></ul><ul><ul><ul><li>int b[ 100 ], x[ 27 ]; </li></ul></ul></ul>
  6. 6. 6.4 Examples Using Arrays <ul><li>Initializers </li></ul><ul><ul><ul><li>int n[ 5 ] = { 1, 2, 3, 4, 5 }; </li></ul></ul></ul><ul><ul><li>If not enough initializers, rightmost elements become 0 </li></ul></ul><ul><ul><ul><ul><li>int n[ 5 ] = { 0 } </li></ul></ul></ul></ul><ul><ul><ul><li>All elements 0 </li></ul></ul></ul><ul><ul><li>If too many a syntax error is produced syntax error </li></ul></ul><ul><ul><li>C arrays have no bounds checking </li></ul></ul><ul><li>If size omitted, initializers determine it </li></ul><ul><ul><ul><li>int n[ ] = { 1, 2, 3, 4, 5 }; </li></ul></ul></ul><ul><ul><li>5 initializers, therefore 5 element array </li></ul></ul>
  7. 7. 1 /* Arrays Example */ 2 /* Histogram printing program */ 3 #include <stdio.h> 4 #define SIZE 10 5 6 int main() 7 { 8 int n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; 9 int i, j; 10 11 printf( &quot;%s%13s%17s &quot;, &quot;Element&quot;, &quot;Value&quot;, &quot;Histogram&quot; ); 12 13 for ( i = 0; i <= SIZE - 1; i++ ) { 14 printf( &quot;%7d%13d &quot;, i, n[ i ]) ; 15 16 for ( j = 1; j <= n[ i ]; j++ ) /* print one bar */ 17 printf( &quot;%c&quot;, '*' ); 18 19 printf( &quot; &quot; ); 20 } 21 22 return 0; 23 }
  8. 8. Element Value Histogram 0 19 ******************* 1 3 *** 2 15 *************** 3 7 ******* 4 11 *********** 5 9 ********* 6 13 ************* 7 5 ***** 8 17 ***************** 9 1 *
  9. 9. 6.4 Examples Using Arrays <ul><li>Character arrays </li></ul><ul><ul><li>String “first” is really a static array of characters </li></ul></ul><ul><ul><li>Character arrays can be initialized using string literals </li></ul></ul><ul><ul><ul><ul><li>char string1[] = &quot;first&quot;; </li></ul></ul></ul></ul><ul><ul><ul><li>Null character '' terminates strings </li></ul></ul></ul><ul><ul><ul><li>string1 actually has 6 elements </li></ul></ul></ul><ul><ul><ul><ul><li>It is equivalent to </li></ul></ul></ul></ul><ul><ul><li>char string1[] = { 'f', 'i', 'r', 's', 't', '' }; </li></ul></ul><ul><ul><li>Can access individual characters </li></ul></ul><ul><ul><ul><li>string1[ 3 ] is character ‘s’ </li></ul></ul></ul><ul><ul><li>Array name is address of array, so & not needed for scanf </li></ul></ul><ul><ul><ul><ul><li>scanf( &quot;%s&quot;, string2 ); </li></ul></ul></ul></ul><ul><ul><ul><li>Reads characters until whitespace encountered </li></ul></ul></ul><ul><ul><ul><li>Can write beyond end of array, be careful </li></ul></ul></ul>
  10. 10. Passing Arrays to Functions <ul><li>Passing arrays </li></ul><ul><ul><li>To pass an array argument to a function, specify the name of the array without any brackets </li></ul></ul><ul><ul><ul><ul><li>int myArray[ 24 ]; </li></ul></ul></ul></ul><ul><ul><ul><ul><li>myFunction( myArray, 24 ); </li></ul></ul></ul></ul><ul><ul><ul><li>Array size usually passed to function </li></ul></ul></ul><ul><ul><li>Arrays passed call-by-reference </li></ul></ul><ul><ul><li>Name of array is address of first element </li></ul></ul><ul><ul><li>Function knows where the array is stored </li></ul></ul><ul><ul><ul><li>Modifies original memory locations </li></ul></ul></ul><ul><li>Passing array elements </li></ul><ul><ul><li>Passed by call-by-value </li></ul></ul><ul><ul><li>Pass subscripted name (i.e., myArray[ 3 ] ) to function </li></ul></ul>
  11. 11. 1 /* 2 Passing arrays and individual array elements to functions */ 3 #include <stdio.h> 4 #define SIZE 5 5 6 void modifyArray( int [], int ); /* appears strange */ 7 void modifyElement( int ); 8 9 int main() 10 { 11 int a[ SIZE ] = { 0, 1, 2, 3, 4 }, i; 12 13 printf( &quot;Effects of passing entire array call &quot; 14 &quot;by reference: The values of the &quot; 15 &quot;original array are: &quot; ); 16 17 for ( i = 0; i <= SIZE - 1; i++ ) 18 printf( &quot;%3d&quot;, a[ i ] ); 19 20 printf( &quot; &quot; ); 21 modifyArray( a, SIZE ); /* passed call by reference */ 22 printf( &quot;The values of the modified array are: &quot; ); 23 24 for ( i = 0; i <= SIZE - 1; i++ ) 25 printf( &quot;%3d&quot;, a[ i ] ); 26 27 printf( &quot; Effects of passing array element call &quot; 28 &quot;by value: The value of a[3] is %d &quot;, a[ 3 ] ); 29 modifyElement( a[ 3 ] ); 30 printf( &quot;The value of a[ 3 ] is %d &quot;, a[ 3 ] ); 31 return 0; 32 } Entire arrays passed call-by-reference, and can be modified Array elements passed call-by-value, and cannot be modified
  12. 12. Effects of passing entire array call by reference: The values of the original array are: 0 1 2 3 4 The values of the modified array are: 0 2 4 6 8 Effects of passing array element call by value: The value of a[3] is 6 Value in modifyElement is 12 The value of a[3] is 6 33 34 void modifyArray( int b[], int size ) 35 { 36 int j; 37 38 for ( j = 0; j <= size - 1; j++ ) 39 b[ j ] *= 2; 40 } 41 42 void modifyElement( int e ) 43 { 44 printf( &quot;Value in modifyElement is %d &quot;, e *= 2 ); 45 }
  13. 13. /* Program to count the no of positive and negative numbers*/ #include< stdio.h > void main( ) { int a[50],n,count_neg=0,count_pos=0,I; printf(“Enter the size of the array ”); scanf(“%d”,&n); printf(“Enter the elements of the array ”); for(I=0;I < n;I++) scanf(“%d”,&a[I]); for(I=0;I < n;I++) { if(a[I] < 0) count_neg++; else count_pos++; } printf(“There are %d negative numbers in the array ”,count_neg); printf(“There are %d positive numbers in the array ”,count_pos); }
  14. 14. Multiple-Dimensional Arrays <ul><li>Multiple Dimensional arrays </li></ul><ul><ul><li>Tables with rows and columns ( m by n array) </li></ul></ul><ul><ul><li>Like matrices: specify row, then column </li></ul></ul>Row 0 Row 1 Row 2 Column 0 Column 1 Column 2 Column 3 a[ 0 ][ 0 ] a[ 1 ][ 0 ] a[ 2 ][ 0 ] a[ 0 ][ 1 ] a[ 1 ][ 1 ] a[ 2 ][ 1 ] a[ 0 ][ 2 ] a[ 1 ][ 2 ] a[ 2 ][ 2 ] a[ 0 ][ 3 ] a[ 1 ][ 3 ] a[ 2 ][ 3 ] Row subscript Array name Column subscript
  15. 15. Initialization of multidimensional arrays: Like the one dimension arrays, 2 dimension arrays may be initialized by following their declaration with a list of initial values enclosed in braces Example: Initializes the elements of first row to zero and second row to 1. int table[2][3]={{0,0,0},{1,1,1}} By surrounding the elements of each row by braces. C allows arrays of three or more dimensions. The compiler determines the maximum number of dimension. The general form of a multidimensional array declaration is: date_type array_name[s1][s2][s3]…..[sn]; Where s is the size of the ith dimension. Some examples are: int survey[3][5][12]; float table[5][4][5][3]; Survey is a 3 dimensional array declared to contain 180 integer elements. Similarly table is a four dimensional array containing 300 elements of floating point type.
  16. 16. example program to add two matrices & store the results in the 3rd matrix #include<stdio.h> #include<conio.h> void main() { int a[10][10],b[10][10],c[10][10],i,j,m,n,p,q; clrscr(); printf(&quot;enter the order of first matrix:&quot;); scanf(&quot;%d %d&quot;,&m,&n); printf(&quot;enter the order of the second matrix &quot;); scanf(&quot;%d %d&quot;,&p,&q); if(m==p && n==q) { printf(&quot;matrix can be added &quot;); printf(&quot;enter the elements of the matrix a&quot;); for(i=0;i < m;i++) { for(j=0;j < n;j++) scanf(&quot;%d&quot;,&a[i][j]); } printf(&quot;enter the elements of the matrix b&quot;); for(i=0;i < p;i++) { for(j=0;j < q;j++) scanf(&quot;%d&quot;,&b[i][j]); }
  17. 17. printf(&quot;the sum of the matrix a and b is&quot;); for(i=0;i < m;i++) { for(j=0;j < n;j++) c[i][j]=a[i][j]+b[i][j]; } for(i=0;i < m;i++) { for(j=0;j < n;j++) printf(&quot;%d &quot;,c[i][j]); printf(&quot; &quot;); } } }
  18. 18. Structure Arrays are used to store large set of data and manipulate them but the disadvantage is that all the elements stored in an array are to be of the same data type. If we need to use a collection of different data type items it is not possible using an array. When we require using a collection of different data items of different data types we can use a structure. Structure is a method of packing data of different types. A structure is a convenient method of handling a group of related data items of different data types. G eneral format: struct tag_name { data type member1; data type member2; … … } Example: struct lib_books { char title[20]; char author[15]; int pages; float price; };
  19. 19. the keyword struct declares a structure to holds the details of four fields namely title, author pages and price. These are members of the structures. Each member may belong to different or same data type. The tag name can be used to define objects that have the tag names structure. The structure we just declared is not a variable by itself but a template for the structure. We can declare structure variables using the tag name any where in the program. For example the statement, struct lib_books book1, book2, book3; declares book1,book2,book3 as variables of type struct lib_books each declaration has four elements of the structure lib_books. The complete structure declaration might look like this struct lib_books { char title[20]; char author[15]; int pages; float price; }; struct lib_books, book1, book2, book3; Structure Contd………
  20. 20. We can also combine both template declaration and variables declaration in one statement, the declaration struct lib_books { char title[20]; char author[15]; int pages; float price; } book1,book2,book3; is valid. book1, book2, book3 declares book1,book2,book3 as structure variables representing 3 books but does not include a tag name for use in the declaration. A structure is usually defines before main along with macro definitions. In such cases the structure assumes global status and all the functions can access the structure. Structure Contd………
  21. 21. Giving values to members: The link between a member and a structure variable is established using the member operator ‘.’ Which is known as dot operator or period operator. For example: Book1.price Is the variable representing the price of book1 and can be treated like any other ordinary variable. We can use scanf statement to assign values like scanf(“%s”,book1.file); scanf(“%d”,&book1.pages); book1.pages=250; book1.price=28.50;
  22. 22. #include<stdio.h> struct student { int id_no; char name[20]; char address[20]; int age; }newstudent; void main() { printf(&quot;Enter the student information&quot;); printf(&quot;Now Enter the student id_no&quot;); scanf(&quot;%d&quot;,&newstudent.id_no); printf(&quot;Enter the name of the student&quot;); scanf(&quot;%s&quot;,&newstudent.name); printf(&quot;Enter the address of the student&quot;); scanf(&quot;%s&quot;,&newstudent.address); printf(&quot;Enter the age of the student&quot;); scanf(&quot;%d&quot;,&newstudent.age); printf(&quot;Student information &quot;); printf(&quot;student id_number=%d &quot;,newstudent.id_no); printf(&quot;student name=%s &quot;,newstudent.name); printf(&quot;student Address=%s &quot;,newstudent.address); printf(&quot;Age of student=%d &quot;,newstudent.age); } EXAMPLE OF STRUCTURE
  23. 23. Initializing structure: Example: Struct student newstudent { 12345, “kapildev”, “Pes college”, 19; }; This initializes the id_no field to 12345, the name field to “kapildev”, the address field to “pes college” and the age field to 19.
  24. 24. Functions and structures: We can pass structures as arguments to functions. Unlike array names however, which always point to the start of the array, structure names are not pointers. As a result, when we change structure parameter inside a function, we don’t effect its corresponding argument. Passing structure to elements to functions: A structure may be passed into a function as individual member or a separate variable. A program example to display the contents of a structure passing the individual elements to a function is shown below. #include<stdio.h> struct emp { int emp_id; char name[25]; char department[10]; float salary; }; void display(int,char []); void main() { static struct emp emp1={125,&quot;sampath&quot;,&quot;operator&quot;,7500.00}; display(emp1.emp_id,emp1.name); } /* function to display structure variables*/ void display(int e_no,char e_name[]) { printf(&quot;%d %s&quot;,e_no,e_name); }
  25. 25. Arrays of structure: It is possible to define a array of structures for example if we are maintaining information of all the students in the college and if 100 students are studying in the college. We need to use an array than single variables. We can define an array of structures as shown in the following example: structure information { int id_no; char name[20]; char address[20]; char combination[3]; int age; } student[100];
  26. 26. An array of structures can be assigned initial values just as any other array can. Remember that each element is a structure that must be assigned corresponding initial values as illustrated below. #include<stdio.h> void main() { struct info { int id_no; char name[20]; char address[20]; int age; }std[100]; int I,n; printf(&quot;Enter the number of students&quot;); scanf(&quot;%d&quot;,&n); printf(&quot; Enter Id_no,name address combination agem&quot;); for(I=0;I<n;I++) scanf (&quot;%d%s%s%d&quot;, &std[I].id_no,std[I].name,std [I].address,&std[I].age); printf(&quot; Student information&quot;); for (I=0;I< n;I++) printf(&quot;%d %s %s %d &quot;,std[I].id_no,std[I].name,std[I].address,std[I].age ); }
  27. 27. Structure within a structure: A structure may be defined as a member of another structure. In such structures the declaration of the embedded structure must appear before the declarations of other structures. struct date { int day; int month; int year; }; struct student { int id_no; char name[20]; char address[20]; int age; struct date def; struct date doa; }oldstudent,newstudent; the sturucture student constains another structure date as its one of its members.
  28. 28. Union Unions like structure contain members whose individual data types may differ from one another. However the members that compose a union all share the same storage area within the computers memory where as each member within a structure is assigned its own unique storage area. Thus unions are used to observe memory. They are useful for application involving multiple members. Where values need not be assigned to all the members at any one time. Like structures union can be declared using the keyword union as follows: union item { int m; float p; char c; } code; this declares a variable code of type union item. The union contains three members each with a different data type. However we can use only one of them at a time. This is because if only one location is allocated for union variable irrespective of size. The compiler allocates a piece of storage that is large enough to access a union member we can use the same syntax that we use to access structure members. That is code.m code.p code.c are all valid member variables.
  29. 29. Pointers Pointer declaration: A pointer is a variable that contains the memory location of another variable. The syntax is as shown below. You start by specifying the type of data stored in the location identified by the pointer. The asterisk tells the compiler that you are creating a pointer variable. Finally you give the name of the variable. type *variable_name Example: int *ptr; float *ptr1; Address operator: Once we declare a pointer variable we must point it to something we can do this by assigning to the pointer the address of the variable you want to point as in the following example: ptr=&num; This places the address where num is stores into the variable ptr. If num is stored in memory 21260 address then the variable ptr has the value 21260.
  30. 30. /* A program to illustrate pointer declaration*/ #include<stdio.h> void main() { int *ptr; int num; num=45; ptr=&num; printf (“ num is %d ”, num); printf (“ The num pointer is %d”,ptr); } Output: num is 45 The num pointer is 45
  31. 31. /* Program to display the contents of the variable their address using pointer variable*/ #include<stdio.h> void main() { int num, *intptr; float x, *floptr; char ch, *cptr; num=123; x=12.34; ch='a'; intptr=&num; cptr=&ch; floptr=&x; printf(&quot;Num %d stored at address %u &quot;,*intptr,intptr); printf(&quot;Value %f stored at address %u &quot;,*floptr,floptr); printf(&quot;Character %c stored at address %u &quot;,*cptr,cptr); }
  32. 32. Pointer expressions & pointer arithmetic Like other variables pointer variables can be used in expressions. For example if p1 and p2 are properly declared and initialized pointers, then the following statements are valid. y = *p1 * *p2; sum = sum + *p1; z = 5* - *p2/p1; *p2 = *p2 + 10; we can also compare pointers by using relational operators the expressions such as p1 >p2 , p1==p2 and p1!=p2 are allowed.
  33. 33. /*Program to illustrate the pointer expression and pointer arithmetic*/ #include<stdio.h> #include<conio.h> void main() { int *ptr1,*ptr2; int a,b,x,y,z; clrscr(); a=30;b=6; ptr1=&a; ptr2=&b; x=*ptr1+ *ptr2-6; y=6* (- *ptr1) / *ptr2 + 30; printf(&quot; Address of a %u&quot;,ptr1); printf(&quot; Address of b %u&quot;,ptr2); printf(&quot; a=%d, b=%d&quot;,a,b); printf(&quot; x=%d,y=%d&quot;,x,y); ptr1=ptr1 + 70; printf(&quot; a=%d, b=%d&quot;,a,b); printf(&quot; Adress of a %u&quot;,ptr1); getch(); }
  34. 35. Pointers and function: The pointer are very much used in a function declaration. Sometimes only with a pointer a complex function can be easily represented and success. The usage of the pointers in a function definition may be classified into two groups. 1. Call by reference 2. Call by value. Call by value: We have seen that a function is invoked there will be a link established between the formal and actual parameters. A temporary storage is created where the value of actual parameters is stored. The formal parameters picks up its value from storage area the mechanism of data transfer between actual and formal parameters allows the actual parameters mechanism of data transfer is referred as call by value. The corresponding formal parameter represents a local variable in the called function. The current value of corresponding actual parameter becomes the initial value of formal parameter. The value of formal parameter may be changed in the body of the actual parameter. The value of formal parameter may be changed in the body of the subprogram by assignment or input statements. This will not change the value of actual parameters.
  35. 36. #include<stdio.h> void swap(int,int); void main() { int x,y; x=20; y=30; printf(&quot; Value of x and y before function call =%d %d&quot;,x,y); swap(x,y); printf(&quot; Value of x and y after function call =%d %d&quot;,x,y); } void swap(int p,int q) { int temp; temp=p; p=q; q=temp; } Output: Value of x and y before function call = 20 30 Value of x and y after function call = 20 30 Example of Call by Value
  36. 37. Call by Reference When we pass address to a function the parameters receiving the address should be pointers. The process of calling a function by using pointers to pass the address of the variable is known as call by reference. The function which is called by reference can change the values of the variable used in the call. /* example of call by reference*? #include<stdio.h> void Swap(int *,int *); void main() { int x,y; x=20; y=30; printf(&quot; Value of x and y before function call =%d %d&quot;,x,y); Swap(&x,&y); printf(&quot; Value of x and y after function call =%d %d&quot;,x,y); } void Swap(int *p,int *q) { int temp; temp=*p; *p=*q; *q=temp; }
  37. 39. Dynamic memory allocation: The process of allocating memory at run time is known as dynamic memory allocation . Although c does not inherently have this facility there are four library routines which allow this function. Many languages permit a programmer to specify an array size at run time. Such languages have the ability to calculate and assign during executions, the memory space required by the variables in the program. But c inherently does not have this facility but supports with memory management functions, which can be used to allocate and free memory during the program execution. The following functions are used in c for purpose of memory management. Function Task malloc Allocates memory requests size of bytes and returns a pointer to the Ist byte of allocated space calloc Allocates space for an array of elements initializes them to zero and returns a pointer to the memory free Frees previously allocated space realloc Modifies the size of previously allocated space.
  38. 40. Allocating a block of memory A block of memory may be allocated using the function malloc. The malloc function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer. It takes the following form: ptr=(cast_type *)malloc(byte-size); ptr is a pointer of type cast-type the malloc returns a pointer (of cast type) to an area of memory with size byte-size. Example: x=(int *)malloc(100*sizeof(int)); On successful execution of this statement a memory equivalent to 100 times the area of int bytes is reserved and the address of the first byte of memory allocated is assigned to the pointer x of type int.
  39. 41. Allocating multiple blocks of memory Calloc is another memory allocation function that is normally used to request multiple blocks of storage each of the same size and then sets all bytes to zero. The general form of calloc is: ptr=(cast_type *) calloc(n,elem_size); The above statement allocates contiguous space for n blocks each size of elements size bytes. All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If there is not enough space a null pointer is returned.
  40. 42. Releasing the used space Compile time storage of a variable is allocated and released by the system in accordance with its storage class. With the dynamic runtime allocation, it is our responsibility to release the space when it is not required. The release of storage space becomes important when the storage is limited. When we no longer need the data we stored in a block of memory and we do not intend to use that block for storing any other information, we may release that block of memory for future use, using the free function. free(ptr); ptr is a pointer that has been created by using malloc or calloc.
  41. 43. To Alter the size of allocated memory The memory allocated by using calloc or malloc might be insufficient or excess sometimes in both the situations we can change the memory size already allocated with the help of the function realloc. This process is called reallocation of memory. The general statement of reallocation of memory is : ptr=realloc(ptr,newsize); This function allocates new memory space of size newsize to the pointer variable ptr and returns a pointer to the first byte of the memory block. The allocated new block may be or may not be at the same region.
  42. 44. #include<stdio.h> #include<stdlib.h> #define NULL 0 void main() { char *buffer; /*Allocating memory*/ if((buffer=(char *)malloc(10))==NULL) { printf(&quot;Malloc failed &quot;); exit(1); } strcpy(buffer,&quot;Bangalore&quot;); printf(&quot; Buffer contains:%s &quot;,buffer); /*Reallocation*/ if((buffer=(char *)realloc(buffer,15))==NULL) { printf(&quot;Reallocation failed &quot;); exit(1); } printf(&quot; Buffer size modified. &quot;); printf(&quot; Buffer still contains: %s &quot;,buffer); strcpy(buffer,&quot;Mysore&quot;); printf(&quot; Buffer now contains:%s &quot;,buffer); /*freeing memory*/ free(buffer); }
  43. 45. Linked List A linked list is called so because each of items in the list is a part of a structure, which is linked to the structure containing the next item. This type of list is called a linked list since it can be considered as a list whose order is given by links from one item to the next. Structure Each item has a node consisting two fields one containing the variable and another consisting of address of the next item(i.e., pointer to the next item) in the list. A linked list is therefore a collection of structures ordered by logical links that are stored as the part of data. Consider the following example to illustrator the concept of linking. Suppose we define a structure as follows struct linked_list { float age; struct linked_list *next; } struct linked_list node1,node2; Item  Item 
  44. 46. Advantages of Linked List A linked list is a dynamic data structure and therefore the size of the linked list can grow or shrink in size during execution of the program. A linked list does not require any extra space therefore it does not waste extra memory. It provides flexibility in rearranging the items efficiently. The limitation of linked list is that it consumes extra space when compared to a array since each node must also contain the address of the next item in the list to search for a single item in a linked list is cumbersome and time consuming.
  45. 47. #include<stdio.h> #include<conio.h> #include<alloc.h> /* structure containing a data part and link part */ struct node { int data ; struct node *link ; }; void append(struct node **,int ); void display(struct node * ); void main( ) { struct node *p; p = NULL ; append ( &p, 14 ) ; append ( &p, 30 ) ; append ( &p, 25 ) ; append ( &p, 42 ) ; append ( &p, 17 ) ; display ( p ) ; } /* adds a node at the end of a linked list */ void append ( struct node **q, int num ) { struct node *temp, *r ; if (*q == NULL) { temp = malloc(sizeof(struct node)) ; temp -> data = num ; temp -> link = NULL ; *q = temp ; } else { temp = *q ; /* go to last node */ while ( temp -> link != NULL ) temp = temp -> link; /* add node at the end */ r = malloc ( sizeof ( struct node ) ) ; r -> data = num ; r -> link = NULL ; temp -> link = r ; } } void display ( struct node *q ) { printf ( &quot; &quot; ) ; /* traverse the entire linked list */ while ( q != NULL ) { printf (&quot; %d &quot;, q -> data ) ; q = q -> link ; } } Example of Linked List
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.