320 likes | 344 Views
Learn the basics of pointers in C, including declaration, operators used with pointers, pointers and arrays, and pointers as function arguments.
E N D
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.
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.
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
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.
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
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
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++
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
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
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
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]
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
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
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.
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
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.
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; }
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!=line, pline - - ); printf(“%c ”,*pline!=line, pline - - ); // Display the last character }
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 !=‘\0’, pline++) { ++cnt; ++ pline; // Come back to the last character } printf(“\n There are %d characters”,cnt); }
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 !=‘\0’, pline++) if (*pline == ch) ++cnt; printf(“\n There are %d occurrence ”,cnt); }
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 !=‘\0’) { cword ++; for ( ; ((pline !=‘\0’) and ( *pline!=‘ ‘); pline++) ; // skips letters for ( ; ((pline !=‘\0’) and ( *pline==‘ ‘); pline++) ; // skips blanks } printf(“There are %d words in the string.”,cword); }
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 !=‘\0’) { printf(“\n”); for ( ; ((pline !=‘\0’) and ( *pline!=‘ ‘); pline++) printf(“%c”,*pline) ; // display letters for ( ; ((pline !=‘\0’) and ( *pline==‘ ‘); pline++) ; // skips blanks } }
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).
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().
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); }
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.
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
Array of Pointers The use of multidimensional arrays with pointers: • To access the element of x[2][5] you can say *(x[2]+5) or *(*(x+2)+5). Example : #include <stdio.h> #include <alloc.h> void main() { int *list[3], j, k; /* Declaration of the multi-dim. array*/ for (j=0; j<3; j++) list[j]=(int*) alloc(5*sizeof(int)); /* Reading numbers into multi-dim arr.*/ for (j=0; j<3;j++) for (k=0; k<5; k++) { printf(“number = “); scanf(“%d”,(*list+j)+k); } /* Writing the content of the arr.*/ for(j=0;j<3;j++) { printf(“\n”); for(k=0;k<5;k++) printf(“%5d “,*(*(list+j)+k)); } } /* End of main()*/
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]); }
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]); }
Array of Pointers e.g.: (Dynamically created array of strings with variable string length) //<< Continues >> int strlen( char *pstr ); { int slen=0; for (; *pstri!=‘\0’; pstr++) slen++; return (slen+1) }