1 / 31

Pointers & Dynamic Memory Allocations in C

Pointers & Dynamic Memory Allocations in C. CHAPTER 3. Pointers verses Variables. Pointers are variables that contains memory addresses. A variable contains a specific value. A pointer contains the address of a variable that contains a specific value.

barto
Download Presentation

Pointers & Dynamic Memory Allocations in C

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Pointers & Dynamic MemoryAllocations in C CHAPTER 3

  2. Pointers verses Variables • Pointers are variables that contains memory addresses. • A variable contains a specific value. • A pointer contains the address of a variable that contains a specific value. • Like other variables, pointer must be declared before they can be used.

  3. Pointer Declaration • Just like variables, each pointer has a name and a data type that can be at the pointed address. e.g.: int *ptr ; // A pointer declaration int cnt=32 ; // A variable declaration … ptr = &cnt ; • Note that, pointer names have an indicator ( * ) character, that is differentiating them from variable names. • At the previous example, ptr is declared as a pointer, which pointing a memory address contains an integer value.

  4. Pointer Declaration • Pointers are indirectly referencing variables. cnt is directly references a variable whose value is 32. 32 cnt ptr is indirectly references a variable whose value is 32. 32 ptr cnt

  5. Operators Used with Pointers • & : The “address of ” operator is used mostly just before any variable name for indicating its memory address. • * : The content of operator is used before a variable name, for indicating the specific value existing at the address pointer contains. • Note that, & operator is used with variables, and * operator is used with pointers.

  6. Operators Used with Pointers e.g.: int x=1, y=2; int *ip; ip = &x; // The address of x is assigned to ip y = *ip; // The content of the address ip has // is copied to the variable y. (y=x) printf(“x=%d y=%d”, x, y); The output will be: x=1 y=1

  7. Operators Used with Pointers e.g.: int x=1; int *ip; ip = &x; *ip = *ip + 10; /* The value 10 is added to the content of the address ip has */ printf(“x=%d *ip=%d”, x, *ip); The output will be: x=11 *ip=11

  8. Operators Used with Pointers e.g.: *ip +=1; is same as ++ *ip; and *ip ++; • All of them above increments the value of the address in ip by 1. e.g.: *(ip++); is indicating the value of the NEXT address, which ip has. *(ip++)  *ip++

  9. Operators Used with Pointers e.g.: #include <stdio.h> void main() { int u=3, v, *pu, *pv; pu = &u; v = *pu; pv = &v; printf(“\n u=%d, *pu = %d”, u, *pu); printf(“\n v=%d, *pv = %d”, v, *pv); } The output will be: u=3, *pu=3 v=3, *pv=3

  10. Operators Used with Pointers e.g.: #include <stdio.h> void main() { int u1, u2, v=3, *pv; u1 = 2 * ( v + 5); pv = &v; u2 = 2 * ( *pv + 5); printf(“\n u1 = %d, u2 = %d”, u1, u2); } The output will be: u1= 16, u2 = 16

  11. Operators Used with Pointers e.g.: #include <stdio.h> void main() { int u=1, v=2, *pv; printf(“\n u = %d, v = %d”, u, v); pv = &u; *pv = 6; printf(“\n u = %d, v = %d”, u, v); pv = &v; *pv = 0; printf(“\n u = %d, v = %d”, u, v); } The output will be: u= 1, v = 2 u= 6, v = 2 u= 6, v = 0

  12. Pointers and Arrays • When an array is declared, the followings are done automatically: • The array size of spaces are allocated within the memory. • A pointer as the array name is declared. • The address of the first location is assigned to the pointer( so, it points the initial array element). • So, the followings are exactly same: myarray = &myarray[0] myarray+1 = &myarray[1] myarray + 9 = &myarray[9]

  13. Pointers and Arrays e.g.: int list[5]=“1, 3, 5, 7, 9}, *pv; pv = list; *(pv+3) = 12; 1 2 3 4 5 List pv 1 2 3 12 5 List pv

  14. Pointers and Arrays e.g.: #include <stdio.h> void main() { int i, list[5]={5,10,15,20,25}, *pv; pv=list; for (i=0; i< 5; i++) *(pv + i)= *(pv+i) + 2; for (i=0; i< 5; i++) printf(“%d ,”,list[i]); } Output will be: 7, 12, 17, 22, 27

  15. Pointers and Arrays e.g.: #include <stdio.h> void main() { int i =0; char line[81], *pv; gets(line); while (*(line+i) !=‘\0’) { printf(“%c”,*(line+i)); i++; } } // End of program • This program reads a line at most 80 character and then displays it character by character.

  16. Pointers and Arrays e.g.: Read elements of an array and find the sum of array elements with using pointers. #include <stdio.h> void main() { int i =0, arr[5], *parr, sum = 0; for(i=0; i<5; i++) { printf(“\n Enter the value of location %d”,i+1); scanf(“%d”, &arr[i]); } parr = arr; for(i=0; i<5; i++) { sum += *(parr+i) } printf(“\n The sum is found %d”,sum); } // End of program

  17. Pointers and Function Arguments • When a variable is used as an argument on a function call, the value of this variable is being passed into the function • if variable is not globally declared, its content can not be altered in the function). • When a pointer is used as an argument on a function call, the address in the pointer is being passed into the function. • So, just like globally declared variables, in the function, the content of a local variable, that its address is passed into the function, can be altered.

  18. Pointers and Function Arguments #include <stdio.h> void funct1(int, int); void funct2(int *, int *); void main() { int u = 1, v = 3; printf(“\n Before calling func1, u=%d , v=%d”,u,v); func1(u, v); printf(“\n After calling funct1, u=%d , v=%d”,u,v); funct2(&u, &v); printf(“\n After calling funct2, u=%d , v=%d”,u,v); } void funct1( int u, int v) { // The Output will be u= 0; v=0; // Before Calling func1 u = 1, v = 3 } // After Calling funct1 u = 1, v = 3 // After Calling funct2 u = 0, v= 0 void funct2( int *pu, int *pv) { *pu= 0; *pv=0; }

  19. Examples e.g.: /* Read a character string and display it in reverse order*/ #include <stdio.h> void main() { char line[81], *pline ; printf(“\n Enter a string of characters :”); gets(line); for (pline=line; *pline !=‘\0’, pline++); // Goes to the last character. pline - -; // Comes back to the last character for (; pline > line; pline - -) // Display characters from last to 2th printf(“%c ”, *pline ); pline--; printf(“%c ”,*pline ); // Display the last character }

  20. Examples e.g.: /* Count the number of characters of a string */ #include <stdio.h> void main() { int cnt = 0; char line[81], *pline ; printf(“\n Enter a string of characters :”); gets(line); for (pline = line; *pline ; pline++) { ++cnt; } printf(“\n There are %d characters”,cnt); }

  21. Examples e.g.: /* Count the occurrence of a character within a string */ #include <stdio.h> void main() { int cnt = 0; char line[81], ch, *pline ; printf(“\n Enter a string of characters :”); gets(line); printf(“\n Enter the target character :”); scanf(“%c”, &ch); for (pline = line; *pline; pline++) if (*pline == ch) ++cnt; printf(“\n There are %d occurrence ”,cnt); }

  22. Examples e.g.: /* Reads a character string and counts the existing words */ #include <stdio.h> void main() { char line[81], *pline ; int cword =0; printf(“\n Enter a string of characters :”); gets(line); for (pline=line; *pline ==‘ ’, pline++); // Skips blanks. while (*pline) { cword ++; for ( ; ((pline !=‘\0’) && ( *pline!=‘ ‘); pline++) ; // skips letters for ( ; ((pline !=‘\0’) && ( *pline==‘ ‘); pline++) ; // skips blanks } printf(“There are %d words in the string.”,cword); }

  23. Examples e.g.: /* Read a character string and display one word each line */ #include <stdio.h> void main() { char line[81], *pline ; printf(“\n Enter a string of characters :”); gets(line); for (pline=line; *pline ==‘ ’, pline++); // Skips blanks. while (*pline) { printf(“\n”); for ( ; ((pline !=‘\0’) && ( *pline!=‘ ‘); pline++) printf(“%c”,*pline) ; // display letters for ( ; ((pline !=‘\0’) and ( *pline==‘ ‘); pline++) ; // skips blanks } }

  24. Dynamic Memory Allocation • The process of allocating and de-allocating memory while the program is in execution is called Dynamic Memory Allocation. • Specially, on a situation which the memory requirement is not possible to be estimated on program design time, the required memory has to be allocated dynamically on run time. • Also, when the allocated memory is not going to be used, on run time, it may be de-allocated (free).

  25. Dynamic Memory Allocation • On memory allocation, a pointer is required to keep the reference address of the allocated memory. • The memory allocation functions are declared within the library <alloc.h>. • malloc(); is the function for allocating a number of bytes within the memory. It returns the reference address of the allocated memory part. • free(); is the function for de-allocating a memory part that was allocated dynamically. • The reference address of the memory part has to be given as argument to free().

  26. Dynamic Memory Allocation • Consider the following code; they are almost same: e.g.: void main() { int list[10]; … } e.g.: void main() { int *list; … list = (int *) malloc(10 * sizeof(int)); … free(list); }

  27. Array of Pointers • It is an array that all its elements are pointers. • Elements of an array of pointer may points some other arrays, which can be think as a multidimensional array. • Really, when a multidimensional array is declared: • A pointer is declared with the name that is equal to the name of the multidimensional array. It points the first element of the array of pointers. • an array of pointer is declared with size of row number of the matrix, and each element points another array with the same data type the multi dimensional array declared.

  28. Array of Pointers int list[5][3] ={1,3,5,7,9,11,13,15,17,19,21,23,25,27,29}; An array of pointers 1 3 5 list 7 9 11 13 15 17 19 21 23 25 27 29 A group of array of integers

  29. Array of Pointers • Array of pointers are mostly used with strings. e.g.: (Dynamically created array of strings with fixed string length) #include <stdio.h> #include <alloc.h> void main() { char *list[10]; int i; /* Declaration of the dynamic array*/ for (i=0; i<10; i++) list[i]= (char *) malloc( 21 * sizeof(char)); /* filling up the array*/ for (i=0; i<10; i++) { printf(“Enter the name %d :”,i+1); scanf(“%s”,list[i]); } /* rewriting names in reverse entry order*/ for (i=9; i>=0; i--) printf(“\n %s”,list[i]); }

  30. Array of Pointers e.g.: (Dynamically created array of strings with variable string length) #include <stdio.h> #include <alloc.h> int strlen( char* ); void main() { char *list[10], line[81]; int i, j, len; for (i=0; i<10; i++) { printf(“\n Enter the name %d =”, i+1); gets(line); len = strlen(line); list[i]= (char *) malloc( len * sizeof(char)); /* copy line to list[i]*/ for (j=0; j<len; j++) *(list[i]+j) = *(line+j); } /* rewriting names in reverse entry order*/ for (i=9; i>=0; i--) printf(“\n %s”,list[i]); }

  31. Array of Pointers e.g.: (Dynamically created array of strings with variable string length) //<< Continues >> int strlen( char *pstr ); { int slen=0; for ( ; *pstri ; pstr++) slen++; return (slen+1) }

More Related