| |
|
Slide 1 :
|
POINTERS Pointers: Fundamentals
void pointer, null pointer
passing pointers to a function
pointers and one dimensional arrays,
dynamic memory allocation
operation on pointers
pointers and multidimensional arrays
array of pointers
pointer to an array
pointers and strings
pointers to function,
pointers and variable length arguments list passing functions to other functions. |
|
|
Slide 2 :
|
POINTERS a pointer is a variable that points to or references a memory location in which data is stored.
Pointers are variables used to store the address of another variable
Each memory cell in the computer has an address that can be used to access that location so a pointer variable points to a memory location we can access and change the contents of this memory location via the pointer.
|
|
|
Slide 3 :
|
A variable name directly references a value.
A pointer indirectly references a value. Referencing a value through a pointer is called indirection.
A variable’s address is the first byte occupied by the variable.
|
|
|
Slide 4 :
|
Why pointer needed Pointers can be used to
Call by address
Return more than 1 value from a function
Pass arrays and strings more conveniently from one function to another
Manipulate arrays more easily by moving pointers to them instead of moving the arrays themselves
Create complex data structures such as linked list and binary trees
Communicate information about memory
Compile faster,more efficient code than other derived data types such arrays |
|
|
Slide 5 :
|
Pointer declaration A pointer variable must be declared before it can be used.
Pointer variable is declared by preceding its name with an asterisk
The declaration of pointers follows this format: type * variable name where type is the data type of the value that the pointer is intended to point to. The asterisk tells the compiler that you are creating a pointer variable. Finally you give the name of the variable.
For example:
int * number;
char * ptr;
|
|
|
Slide 6 :
|
Pointer Variable Declaration |
|
|
Slide 7 :
|
Declaring Pointer Variables |
|
|
Slide 8 :
|
Address operator & & -- "address operator" which gives the memory address of a variable
Indirection operator* Indirection operator also called Dereference operator |
|
|
|
|
|
|
Slide 11 :
|
Placement of the indirection operator before a pointer is said to dereference the pointer.
The value of a dereferenced pointer is not the address.it is the value of a variable that points to |
|
|
Slide 12 :
|
main()?
{
int i=3;
int *j;
j=&i;
printf("%u\n",&i);
printf("%u\n",j);
printf("%u\n",&j);
printf("%d\n",i);
printf("%d\n",*(&i));
printf("%u\n",*j);
}
6485
6485
3276
3
3
3 3 6485 i j 3276 6485 |
|
|
Slide 13 :
|
Initializing Pointers Like other variables, always initialize pointers before using them!!!
For example:
int main(){
int x=3;
int *p;
printf("%d",p); /*donn’t*/
p = &x;
printf("%d",*p); /* Correct */
} |
|
|
Slide 14 :
|
Initializing Pointer Variables |
|
|
Slide 15 :
|
Pointers defined to be of a specific type cannot hold the address of any other type of variable
eg: float *fptr;
int min;
fptr=&min; //error
Any number of pointer can point to same address
|
|
|
Slide 16 :
|
One Variable with Many Pointers int a;
int *p,*q,*r;
p=&a;
q=&a;
r=&a; |
|
|
Slide 17 :
|
PROGRAM Using A Variable with Many Pointers |
|
|
Slide 18 :
|
PROGRAM Using A Variable with Many Pointers |
|
|
|
|
|
|
Slide 21 :
|
PROGRAM 9-3 Add Two Numbers Using Pointers |
|
|
Slide 22 :
|
PROGRAM 9-3 Add Two Numbers Using Pointers |
|
|
Slide 23 :
|
Add Two Numbers Using Pointers
|
|
|
Slide 24 :
|
void pointers The void type of pointer is a special type of pointer.
void pointers can point to any data type
For example
int a=5;
void *vp;
vp=&a;
Pointers to void cannot be directly dereferenced like other pointer variables , by using *
If we want to refer the value of void pointer type casting is required
For example
printf(“a=%d”,*((int *)vp)); will print a=5
|
|
|
Slide 25 :
|
Null pointer A null pointer is a special pointer ,value that is known (generally takes a value as zero),not to point anywhere.
NULL pointer is a pointer which is not pointing to any valid memory address.
NULL is macro constant which has been defined in several header file including stdio.h, alloc.h,mem.h, stdlib.h as
#define NULL 0
We can initialize a pointer to null pointer as
int *ptr=NULL;
We can also use constant value 0
int *ptr=0;
|
|
|
Slide 26 :
|
The difference between void pointers and NULL pointers: A Void pointer is a special type of pointer of void and denotes that it can point to any data type. NULL pointers can take any pointer type, but do not point to any valid reference or memory address.
|
|
|
Slide 27 :
|
Passing pointers to function When an argument is passed by reference, (i.e., when a pointer is passed to a function), the address of a data item is passed to the function.
When passing pointer as arguments to a function formal pointer arguments that must each be preceded by an asterisk.
Function prototypes are written in the same manner. If a function declaration does not include variable names, the data type of each pointer argument must be followed by an asterisk.
|
|
|
|
|
Slide 29 :
|
Returning more than 1 value from a function A function will return only 1 value at a time when passing arguments by value.
using pointers, function can return more than 1 value
#include
float areaperi(float,float *);
void main()
{
float r,area,perimeter;
printf(“Enter radius:”);
scanf(“%f”,&r);
area=areaperi(r,&perimeter);
printf(“Area=%f”,area);
printf(“perimeter=%f”,perimeter);
}
|
|
|
Slide 30 :
|
float areaperi(float r,float *p)
{
float a;
a=3.14*r*r;
p=3.14*2*r;
return a;
}
Here we are passing the arguments value of radius and address of variable perimeter. As we are passing the address of perimeter changes made to variable will be effective in main() also. |
|
|
Slide 31 :
|
pointers and one dimensional arrays The name of an array is a pointer constant (address constant) to the first element.
Since the array name is a pointer constant to the first element, the address of the first element and the name of the array both represent the same location in memory
Name of the array is the beginning address of the array , called the base address of the array |
|
|
Slide 32 :
|
FIGURE Pointers to Arrays |
|
|
Slide 33 :
|
same a &a[0]
a is a pointer only to the first element. Note |
|
|
Slide 34 :
|
34 printf(“%u%u”,a,&a[0]); 2147478270 2147478270 a+1 a+2 a+3 a+4 |
|
|
Slide 35 :
|
We can access array elements in different ways
a[i]
*(a+i);
*(i+a);
i[a] |
|
|
Slide 36 :
|
Output of the program is A pointer when incremented its always pointing to immediately next location of its type Accessing array elements by pointers is always faster than accessing them by subscripts. |
|
|
Slide 37 :
|
Passing array to function
When passing array to the function formal argument of the function may be
int a[] or int *a
/* Demonstration of passing an array to a function */
Void main( )
{ int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
display ( num, 6 ) ;
}
display ( int num[], int n )
{ int i ;
for ( i = 0 ; i <= n - 1 ; i++ )
{
printf ( "\nelement = %d", num[i] ) ;
}
} |
|
|
Slide 38 :
|
passing the address of the zeroth element of the array to a function is as good as passing the entire array to the function
display(&num[0],6) is same as display(num,6); main()
{ int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
display ( &num[0], 6 ) ;
}
display ( int *j, int n )
{ int i ;
for ( i = 0 ; i <= n - 1 ; i++ )
{
printf ( "\nelement = %d", *j ) ;
j++ ; /* increment pointer to point to next element */
}
} |
|
|
Slide 39 :
|
Difference between array name and pointer When memory allocated for the array ,starting address is fixed .i.e it cannot be changed during program execution
Arrayname cann’t used as lvalue.but pointer used as l value
For ex:
|
|
|
Slide 40 :
|
Array cannot be assigned to another but two pointer variable can be assigned
|
|
|
Slide 41 :
|
&operator returns address of operand.When &operator applied to an array it has the same value as the array reference without operator. For pointers it has an independent address
|
|
|
Slide 42 :
|
Sizeof operator returns number of bytes occupied by the array .in the case of pointers it returns 2 or 4 or more bytes of storage i.e number of bytes used to store pointer variable
|
|
|
Slide 43 :
|
Difference between array and pointer |
|
|
Slide 44 :
|
Dynamic memory allocation The process of allocating memory at run time is known as dynamic memory allocation. The process of allocating memory at compile-time is known as Static memory allocation |
|
|
Slide 45 :
|
An important advantage of dynamic memory allocation is the ability to reserve as much memory as may be required during program execution, and then release this memory when it is no longer needed |
|
|
Slide 46 :
|
Memory allocation process In general global variables are allocated storage at compile time. The program instructions and global and static variables are stored in a region known as permanent storage area.
Local variables are stored in another area called stack.
Memory allocated by C’s dynamic allocation functions come from the “heap”: the region of free memory that lies between your program’s permanent storage area and the stack.
FIGURE : A Conceptual View of Memory |
|
|
Slide 47 :
|
Storage of C program |
|
|
Slide 48 :
|
Computer Science: A Structured Programming Approach Using C 48 FIGURE Accessing Dynamic Memory |
|
|
Slide 49 :
|
Memory Management Functions |
|
|
Slide 50 :
|
These functions are defined in stdlib.h |
|
|
Slide 51 :
|
Prototype of malloc: void *malloc(size_t size);
size_t is defined in header file as unsigned integer
Size is the amount of memory we wish to allocate
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.
Eg:
p =(int *)malloc(50*sizeof(int));//(int *) forces void pointer
//to become a integer pointer
malloc() |
|
|
Slide 52 :
|
If p is returning NULL then will terminate from the program |
|
|
Slide 53 :
|
Protype : void *calloc(size_t num_elements, size_t element_size);
Allocate a block of num_elements * element_size bytes
initialize every byte to zero
return pointer to the first byte block or NULL if unable to allocate block
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 elem-size bytes.
int *p;
p = (int *) calloc(100,sizeof(int));//(int *) forces the void
// pointer to become an int pointer calloc() |
|
|
Slide 54 :
|
With the dynamic runtime allocation, it is our responsibility to release the space when it is not required.
free( ) function is the opposite of malloc( ). It returns previously allocated memory to the system.
prototype :void free(void *ptr);
ptr is a pointer to a memory block, which has already been created by malloc or calloc.
General form is free(ptr);
Note: It is not the pointer that is being released but rather what
it points to.
To release an array of memory that was allocated by calloc we need only to release the pointer once. It is an error to attempt to release elements individually.
free() |
|
|
|
|
Slide 56 :
|
Prototype:void *realloc(void *ptr, size_t new_size);
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 resized block. The allocated new block may be or may not be at the same region.
realloc() |
|
|
|
|
Slide 58 :
|
MEMSET() function To set all the bytes in a block of memory to a particular value, use memset().
The function prototype is
void * memset(void *s, int c, size_t n);
Set s first n bytes of s to byte c
Ex:
void main()
{
char message1[] = “hello world\n";
printf("\nmessage1[] before memset():\t%s", message1); memset(message1 , `@', strlen(message1)-1);
printf("\nmessage1[] after memset():\t%s", message1);
}
o/p is
message1[] before memset():hello world
message1[] after memset():**********
|
|
|
Slide 59 :
|
operation on pointers (pointer arithmetic) Following operation is possible on pointers
A pointer variable can be assigned the address of an ordinary variable
e.g., pv = &v).
A pointer variable can be assigned the value of another pointer variable
(e.g., pv= px) provided both pointers point to objects of the same data type .
A pointer variable can be assigned a null (zero)
An integer may be added to or subtracted from a pointer.
Pointer variables may be subtracted from one another.
Pointer variables can be used in comparisons, if they are of same type
|
|
|
Slide 60 :
|
Cann’t perform following operation on pointers
Addition of 2 pointers
Multiplying a pointer with a number
Division of pointer by number |
|
|
Slide 61 :
|
int a[10], *p, *q,*ip; void *vp;
p = &a[2];
q = p + 3; /* q points to a[5] now */
p = q – 1; /* p points to a[4] now */
p++; /* p points to a[5] now */
p--; /* p points to a[4] now */
*p = 123; /* a[4] = 123 */
*q = *p; /* a[5] = a[4] */
q = p; /* q points to a[4] now */
vp=ip //pointer to void can be freely converted back and forth with any type |
|
|
Slide 62 :
|
*ptr++
increments the pointer
equivalent to
int temp; temp=ptr;ptr=ptr+1
++*ptr
increment the value pointed by pointer
equivalent to ++(*ptr)
i.e int temp;
*ptr=*ptr+1;
temp=*ptr;
*(++ptr)
equivalent to
int temp;ptr=ptr+1 temp=ptr;
(*ptr)++
Equivalent to
int temp;temp=*ptr;*ptr=*ptr+1;
|
|
|
Slide 63 :
|
Example
void main()
{
int a[]={10,20,30,40}
int *ptr,i;
ptr=a;
printf(“*ptr:%d”,*ptr);
i=*(ptr++);
printf(“i:%d”,i);
printf(“*ptr:%d”,*ptr);
i=(*ptr)++;
printf(“i:%d”,i);
printf(“*ptr:%d”,*ptr);
i=++(*ptr);
printf(“i:%d”,i);
printf(“*ptr:%d”,*ptr); i=*(++ptr); printf(“i:%d”,i);
printf(“*ptr:%d”,*ptr); Output
*ptr=10
i:10
*ptr:20
i:20
*ptr=21
i:30
*ptr:30
i:31
*ptr:31
|
|
|
Slide 64 :
|
Subtraction of one pointer from another.
One pointer variable can be subtracted from another provided both variables point to elements of the same array.
The resulting value indicates the number of elements separating them.
Ex:
main( )
{
int arr[ ] = { 10, 20, 30, 45, 67, 56, 74 } ;
int *i, *j ;
i = &arr[2] ;
j = &arr[5] ;
printf ( "%d %d", j - i, i - j, ) ; } //will output 3,-3
|
|
|
Slide 65 :
|
Comparison of two pointer variables
Pointer variables can be compared provided both variables point to objects of the same data type.
Ex:
main( )
{
int arr[ ] = { 10, 20, 36, 72, 45, 36 } ;
int *j, *k ;
j = &arr [ 4 ] ;
k = ( arr + 4 ) ;
if ( j == k )
printf ( "The two pointers point to the same location" ) ;
else
printf ( "The two pointers do not point to the same location" ) ;
}
|
|
|
Slide 66 :
|
Pointers to pointers a pointer which contains another pointer’s address
main ()
{
int i = 3 ;
int * j ;
int * * k ; //pointer to pointer to an integer
j = & i ;
k = & j ;
printf (“\n address of i = %d”, & i ); 6485
printf (“\n address of i = %d”, j ); 6485
printf (“\n address of i = %d”, * k ); 6485
Printf(“Value of i=%d”,**k); 3
printf (“\n address of j = %d”, & j ); 3276
printf (“\n address of j = %d”, k ); 3276
printf (“\n address of k = %d”, & k ); 7234
}
3 i 6485 6485 j 3276 3276 k 7234 |
|
|
|
|
Slide 68 :
|
A 2D array is actually a collection of 1D array.so we can define a 2D array as a collection of 1D arrays. pointers and multidimensional arrays, Fig:Physical representation of 2 dimensional array a[3][2] |
|
|
Slide 69 :
|
We know a[i] = *(a+i) .in same manner 2d array can be expressed as
a[i][j]= *(a[i]+j)=(*(a+i))[j]=*(*(a+i)+j) Suppose x is 2d array of 10 rows and 15 columns To access the element at 2 nd row 5 th column (x[2][5] )can be accessed by any of the following methods
* ( x[2] + 5)
(*(x+2))[5]
*( * ( x + 2 ) + 5 )
|
|
|
|
|
Slide 71 :
|
pointers and strings we can represent strings using pointers
Consider the declarations
char s[]=“good”;
char *ptr=“good”;
First declaration allocates 5 bytes of memory for the array
s
Second declaration tells the compiler allocate space in memory for ptr.puts the string constant ”good” in memory and initialise ptr with base address of string constant.
ptr
s[0] s[1] s[2] s[3] s[4] |
|
|
Slide 72 :
|
//Example program for length of string using pointers
void main( )
{
char arr[ ] = “Hai" ;
int len1, len2 ;
len1 = strlenptr( arr ) ;
len2 = strlenptr ( “Hello" ) ;
printf ( "\nstring = %s length = %d", arr, len1 ) ;
printf ( "\nstring = %s length = %d", “Hello", len2 ) ;
}
strlenptr ( char *s )
{
int length = 0 ;
while ( *s != '\0' )
{
length++ ;
s++ ;
}
return ( length ) ;
} |
|
|
Slide 73 :
|
we cannot assign a string to another, whereas, we can assign a char pointer to another char pointer. main( )
{
char str1[ ] = "Hello" ;
char str2[10] ;
char *s = "Good Morning" ;
char *q ;
str2 = str1 ; /* error */
q = s ; /* works */
}
|
|
|
Slide 74 :
|
main( )
{
char str1[ ] = "Hello" ;
char *p = "Hello" ;
str1 = "Bye" ; /* error */
p = "Bye" ; /* works */
}
once a string has been defined it cannot be initialized to another set of characters. Unlike strings, such an operation is perfectly valid with char pointers. |
|
|
Slide 75 :
|
array of pointers an array of pointers are collection of addresses.
The addresses present in the array of pointers can be addresses of variables or addresses of array elements or any other addresses.
main( )
{
int *arr[4] ; /* array of integer pointers */
int i = 31, j = 5, k = 19, l = 71, m ;
arr[0] = &i ;
arr[1] = &j ;
arr[2] = &k ;
arr[3] = &l ;
for (m = 0 ; m <= 3 ; m++ )
printf ( ”\n %d ", * ( arr[m] ) ) ;
} |
|
|
|
|
Slide 77 :
|
A multidimensional array can be expressed in terms of an array of pointers.
In such situations the newly defined array will have one less dimension than the original multidimensional array.
a two-dimensional array can be defined as a one-dimensional array of pointers by writing
data - type *array[ expression 1 ] ;
rather than the conventional array definition,
data- type array[ expression 1] [ expression 2] ;
|
|
|
Slide 78 :
|
Suppose x is a two-dimensional integer array having 10 rows and 20 columns,
We can define x as a one-dimensional array of pointers by writing
int * x [ l O ] ;
Hence, x[ 01 points to the beginning of the first row, x[ 1 ] points to the beginning of the second row, and so on.
Note that the number of elements within each row is not explicitly specified. |
|
|
|
|
Slide 80 :
|
#include
#include
#define MAXROWS 20
/* function prototypes */
void readinput (int *a[MAXROWS], int nrows, int ncols);
void computesums(int *a[MAXROWS], int *b[MAXROWS],int *c[MAXROWS], int nrows, int ncols);
void writeoutput(int *c[MAXROWS], int nrows, int ncols);
main( )
{
………………….
int *a[MAXROWS], *b[MAXROWS], *c[MAXROWS]; ……………………………..
/* allocate i n i t i a l memory */
f o r (row = 0; row < nrows; ++row) {
a[row] = ( i n t *) malloc (ncols * s i z e o f ( i n t ) ) ;
b[row] = ( i n t *) malloc (ncols * s i z e o f ( i n t ) ) ;
c[ row] = ( i n t *) malloc (ncols * sizeof ( i n t ) ) ;
|
|
|
Slide 81 :
|
readinput(a, nrows, ncols);
readinput(b, nrows, ncols);
computesums(a, b, c, nrows, ncols);
p r i n t f ("\n\nSums of the elements: \ n \ n " ) ;
writeoutput(c, nrows, ncols);
}
v o i d r e a d i n p u t ( i n t *a[MAXROWS], i n t m, i n t n)
{
i n t row, col;
f o r (row = 0; row < m; ++row)
{
p r i n t f ( ” \ n E n t e r data f o r row no. %2d\nn, row + 1);
f o r ( c o l = 0; c o l < n; ++col)
scanf(“%d”, (a [row ]+ c o l ) ) ;
}
return;
}
|
|
|
Slide 82 :
|
void w r i t e o u t p u t ( i n t *a[MAXROWS], i n t m, i n t n)
{
i n t row, col;
f o r (row = 0; row < m; ++row) {
f o r ( c o l = 0; c o l < n; ++col)
p r i n t f ( “% 4 d “ , * (a[row] + c o l ) ) ;
p r i n t f ( “ \n”) ;
}
return;
}
void computesums(int *a[MAXROWS], i n t *b[MAXROWS], i n t *c[MAXROWS], i n t m, i n t n)
i n t row, col;
f o r (row = 0; row < m; ++row)
f o r ( c o l = 0; c o l < n; ++col)
* ( c [ row] + c o l ) = *(a [row] + c o l ) + * ( b[row] + c o l ) ;
return;
}
|
|
|
Slide 83 :
|
Array of pointers to strings An array of character pointers that is pointed to string can be declared as
char *nameptr[MAX];
array nameptr is an array of size Max;
Each element of the array is a character pointer
Ex:
char *names[ ] = {
"akshay",
"parag",
"raman",
"srinivas",
"gopal",
"rajesh"
} ; Here names[ ] is an array of pointers. It contains base addresses of respective names |
|
|
|
|
Slide 85 :
|
An advantage of array of pointers to string is that a fixed block of memory need not be reserved in advance
Another advantage of array of pointers is that pointers can be reordered in any manner without moving data items
Limitation of array of pointers to strings is we can't receive strings from keyboard using scanf().we can only initialize the strings at the place where we are declaring the array.
|
|
|
Slide 86 :
|
pointer to an array Like pointer to integer we can pointer to an array
We can express 2d using pointer to an array.the 2d array declaration will be
data- type ( *ptvar) [ expression 2] ;
rather than
data- type array[ expression I] [ expression 2];
output is 65500 65500
65502 65504 /* Usage of pointer to an array */
main( )
{
int a[][2] = {
1,2,
3,4,
5,6,
} ;
int *p;
int (*q)[2]; //q is an pointer to an array of 2 integers
p=(int *)a;
q=a; printf(“%u%u\n”,p,q);
p++;
q++; Printf(“%u%u\n”,p,q); } |
|
|
Slide 87 :
|
While passing 2d array to function we can use pointer to an array
Example
void show(int ( *q )[4], int row, int col );
main( )
{
int a[3][4] = {
1, 2, 3, 4,
5, 6, 7, 8,
9, 0, 1, 6
} ;
show ( a, 3, 4 ) ; } void show ( int ( *q )[4], int row, int col )
{
int i, j ;
int *p ;
for ( i = 0 ; i < row ; i++ )
{
p = q + i ;
for ( j = 0 ; j < col ; j++ )
printf ( "%d ", * ( p + j ) ) ; //same as //*(*(q+i)+j)
printf ( "\n" ) ;
}
printf ( "\n" ) ;
} |
|
|
Slide 88 :
|
Difference between array of pointer and pointer to an array |
|
|
Slide 89 :
|
Pointers to function A pointer to a function points to the address of the function.
You can use pointers to call functions and to pass functions as arguments to other functions.
You cannot perform pointer arithmetic on pointers to functions.
A declaration of a pointer to a function must have the pointer name in parentheses.
General format of declaration of function pointer is
Return- type(*function –pointer- name)(type 1 arg 1 , type 2 arg 2, . . )
|
|
|
Slide 90 :
|
Consider the declarations
int *f(int a); /* function f returning an int* */
int (*g)(int a); /* pointer g to a function returning an int*/
In the first declaration, f is interpreted as a function that takes an int
as argument, and returns a pointer to an int.
In the second declaration, g is interpreted as a pointer to a function that
takes an int argument and that returns an int. () has a higher precedence than the dereference operator *. Without them, the compiler interprets the statement as a function that returns a pointer to a specified return type. |
|
|
Slide 91 :
|
Initializing Function Pointers Like other pointer variable ,function pointer must be initialised prior to use
To initialize a function pointer, you must give it the address of a function in your program.
#include
void (*foo)(int);
void myfunc(int x)
{
printf( "%d\n", x );
}
void main()
{
foo = myfunc;
} |
|
|
Slide 92 :
|
Calling a function using function pointer to call the function pointed to by a function pointer, use the name of the function pointer
EX:
#include
void (*foo)(int);
void myfunc(int x)
{
printf( "%d\n", x );
}
void main()
{ foo = myfunc;
//To call myfunc
foo( 2 );
//if we want we can use(*foo)(2)
(*foo)( 2 ); } |
|
|
Slide 93 :
|
Uses of pointers to function In writing memory resident programs
In writing viruses or vaccines to remove the viruses
In developing COM/DCOM components
In VC++ programming to connect events to function call
|
|
|
Slide 94 :
|
pointers and variable length arguments list For implementing variable number of arguments 3 macros are availble in “stdarg.h” called va_start ,va_arg, va_end.
va_start-which initializes pointer to the beginning of the list of optional arguments list,
va_arg,-which returns the next argument in the list,
va_end-which cleans up the variable argument list.
|
|
|
Slide 95 :
|
to use these macros , we need a variable capable of storing a variable-length argument list--this variable will be of type va_list. va_list is like any other type.
va_list a_list; va_start is a macro which accepts two arguments, a va_list and the name of the Variable va_arg takes a va_list and a variable type, and returns the next argument in the list in the form of whatever variable type it is told. |
|
|
Slide 96 :
|
#include
#include
double average ( int num, ... )
{ va_list arguments;
double sum = 0;
va_start ( arguments, num );
for ( int x = 0; x < num; x++ )
{
sum += va_arg ( arguments, double );
}
va_end ( arguments ); // Cleans up the list
return sum / num;
}
int main()
{
printf( "%f\n", average ( 3, 12.2, 22.3, 4.5 ) ); /*3 indicates the number of values to average)*/
printf( "%f\n", average ( 5, 3.3, 2.2, 1.1, 5.5, 3.3 ) );
} |
|
|
Slide 97 :
|
PASSING FUNCTIONS TO OTHER FUNCTIONS A pointer to a function can be passed to another function as an argument.
We refer to the first function as the guest function, and the second function as the host function.
In its simplest form, the formal argument declaration can be written as
data- type (* function-name) ( )
where data- type refers to the data type of the quantity returned by the guest and function-name is the name of the guest.
|
|
|
Slide 98 :
|
The formal argument declaration can also be written as
data-type (* function-name) ( type 1 , type 2, . . . )
or as
data-type (* function-name) ( type 1 arg 1 , type 2 arg 2, . . . )
Both the indirection operator and the guest function name must be enclosed in parentheses;
(* function-name) (argument 1, argument 2, . . . , argument n) ;
where argument I, argument 2, . . . , argument n refer to the arguments that are required in the function call The guest function can be accessed within the host by means of the indirection operator.For that indirection operator must precede the guest function name .
|
|
|
Slide 99 :
|
function declaration for the host function.
It may be written as
funct- data- type funct-name( arg-data-type (*) ( type 1 , type 2, . . ), where funct-data- type refers to the data type of the quantity returned by the host function;
funct-name refers to the name of the host function;
arg-data- type refers to the data type of the quantity returned by the guest function
type 1, type 2,. . . refer to the data types of guest function’s arguments. data types of other funct args); pointer to guest function |
|
|
Slide 100 :
|
int process(int ( * ) ( int , int ) ) ; /* function declaration (host) */
int functl ( int , int ) ; /* function declaration (guest) */
int funct2(int, int ) ; /* function declaration (guest) */
main( )
{
int i,j;
. . . . .
i= process(funct1); / * pass funct l to process; return a value f o r i*/
. . . . .
j = process(funct2); I* pass funct2 t o process; return a value f o r j */
. . . . .
}
process(int ( * p f ) ( i n t , i n t ) ) /* host function d e f i n i t i o n */
/* (formal argument is a pointer to a function) */
{
int a, b, c;
. . . . .
c = (*pf)(a, b); / * access the function passed t o t h i s function;
return a value f o r c */
. . . . .
return(c);
} |
|
|
Slide 101 :
|
f u n c t l (a, b) /* guest function d e f i n i t i o n */
int a, b;
{
int c;
c = . . . / * use a and b t o evaluate c */
return(c);
}
funct2(x, y) /* guest function d e f i n i t i o n */
int x, y;
{
int z;
z = . . . /* use x and y to evaluate z */
return(z);
} |
|
|
Slide 102 :
|
STRUCTURE and union Defining a structure
processing a structure
user defined data types
structure and pointers,
passing structure to function,
self-referential structures
union. |
|
|
Slide 103 :
|
STRUCTURE A structure is a user defined data type.
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.
When we require using a collection of different data items of different data types we can use a structure.
A STRUCTURE is a collection of variables of different types.
Variables in a structure are called MEMBERS or FIELDS, and are accessed by their name.
Variables in an array are called ELEMENTS, and are accessed using square brackets an an index. |
|
|
Slide 104 :
|
DEFINING A STRUCTURE Declaring a structure requires the struct keyword, followed by a name. Then you declare your collection of members between a pair of curly brackets.
struct structure-tag-name { data type member1; data type member2; … } ; The individual members can be ordinary variables, pointers, arrays, or other structures.
|
|
|
Slide 105 :
|
Fig: Tagged Structure Format |
|
|
Slide 106 :
|
We can declare structure variables as struct structure_name var1,var2,…..,var n;
So we can declare structure variables stud1, stud2 as struct student stud1,stud2;
it is possible to combine the declaration of structure combination with that of the structure variables.
struct structure_name { type element 1; type element 2; …………….. type element n; }variable1,variable2… ; Ex: struct student { int rollno; char name[25]; float totalmark; } stud1, stud2; |
|
|
Slide 107 :
|
Structure type declaration doesnot tell compiler to reserve space in memory .memory will be allocated once variables declared.
We can declare and/or define the structure in 3 ways
Variable structure
Tagged structure
Type-defined structure
Variable structure can be defined as struct
{
memberlist
}variable identifier; Ex
struct
{
int x;
int y;
}a; |
|
|
Slide 108 :
|
It's best to declare structure is in the global area of the program before main.
The size of a struct is the sum of the sizes of all the variables it holds. |
|
|
Slide 109 :
|
Initializing of Structure Structure members can be initialized at declaration.
the initial value must appear in the order in which they will be assigned to their corresponding structure members,enclosed in braces and seperated by commas .
The general form is
struct stucture_name structure-variable={constant1,constant2,..};
or struct structure_name { type element1;
…………….. }structure –variable={constant1,constant2,….}; |
|
|
Slide 110 :
|
Ex:
struct student { char *name; int rollno; float totalmark; } stud1={"Ashraf",1,98};
main()
{
struct student stud2={"Rahul",3,97};
………..
}
structure that are not explicitly initialized will be initialized by the system . For integer and float default value is 0 and char and string type members the default value is ‘\0’;
|
|
|
Slide 111 :
|
111 FIGURE Initializing Structures |
|
|
Slide 112 :
|
Processing of structure |
|
|
Slide 113 :
|
Accessing structure members
Individual members of a struct variable may be accessed using the structure member operator (the dot, “.”).
A structure member can be accessed by writing
variable. member
where variable refers to-the name of a structure-type variable, and member refers to the name of a member within the structure
Ex: to access rollno:of student we can done by stud1.rollno |
|
|
Slide 114 :
|
#include struct student { char name[10]; float marks; } stud1, stud2; void main ( ) { stud1.name = "Tom"; stud2.marks = 99.9; printf (" Name is %s \n", stud1.name); printf (" Marks are %f \n", stud2.marks); }
Example program for structure |
|
|
Slide 115 :
|
//program demonstrating structure
main( )
{
struct book
{
char name ;
float price ;
int pages ;
} ;
struct book b1, b2, b3 ;
printf ( "\nEnter names, prices & no. of pages of 3 books\n" ) ;
scanf ( "%c %f %d", &b1.name, &b1.price, &b1.pages ) ;
scanf ( "%c %f %d", &b2.name, &b2.price, &b2.pages ) ;
scanf ( "%c %f %d", &b3.name, &b3.price, &b3.pages ) ;
printf ( "\nAnd this is what you entered" ) ;
printf ( "\n%c %f %d", b1.name, b1.price, b1.pages ) ;
printf ( "\n%c %f %d", b2.name, b2.price, b2.pages ) ;
printf ( "\n%c %f %d", b3.name, b3.price, b3.pages ) ; } |
|
|
Slide 116 :
|
Copying and comparing structures Structure can be assigned to another structure of same type
Ex:
struct Student s1,s2;
s1.name = "Joe ";
…
s2 = s1;
Copies the entire structure |
|
|
Slide 117 :
|
How Structure Elements are Stored elements of a structure are always stored in contiguous memory locations.
main( )
{
struct book
{
char name ;
float price ;
int pages ;
} ;
struct book b1 = { ‘B', 130.00, 550 } ;
printf ( "\nAddress of name = %u", &b1.name ) ;
printf ( "\nAddress of price = %u", &b1.price ) ;
printf ( "\nAddress of pages = %u", &b1.pages ) ;
} Output
Address of name = 65518
Address of price = 65519
Address of pages = 65523 |
|
|
|
|
Slide 119 :
|
Array of structures It is possible to define a array of structures
General format of declaration of array of structure is
struct tag_name { data type member1; data type member2; … … } structure-variable[index];
Or
struct structure-name structure-variable[index]; |
|
|
Slide 120 :
|
#include
#include
struct student
{
char name[20];
int roll;
int mark;
}s1[10];
void main()
{ int n,i;
clrscr();
printf("Enter the number of students:");
scanf("%d",&n);
for(i=0;i
|
|
|
Slide 121 :
|
Initializing arrays of structures Arrays of structure can be initialized in the same way as arrays
General form
struct structure-name
{
datatype member1;
.
.
};
Struct structure-name structure-variable[N]=
{ constant01,constant02,……constant0n},
{ constant11,constant12,……constant1n},
….
{ constantN1,constantN2,……constantNn},
|
|
|
Slide 122 :
|
Example
struct marks { int subject1; int subject2;
int subject3; };
struct marks student[3]=
{ { 45,68,81},{75,53,69},{57,36,71} }; |
|
|
|
|
Slide 124 :
|
Nesting of structures Structures can contain other structures as members; in other words, structures can nested.
Dot operator with structure variable are used to access the members of inner and outer structures
To access member of inner structure, general form is
Ex: variable. member. submember |
|
|
Slide 125 :
|
We can access members of inner structures as |
|
|
|
|
Slide 127 :
|
User defined data types(typedef) The typedef feature allows users to define new data-types that are equivalent to existing data types
No new data types are produced but an alternative name given to known data types.
In general terms, a new data type is defined as
typedef type new- type;
where type refers to an existing data type
and new- type refers to the new user-defined data type.
Typedef statement doesn’t occupy storage :simply defines a new type
Ex:
typedef int age;
age male, female; it equivalent to int male,female;
|
|
|
Slide 128 :
|
Typedef in structure(typedefined structure declaration) The typedef feature is convenient when defining structures, since it eliminates the need to repeatedly write struct tag whenever a structure is referenced. Hence, the structure can be referenced more concisely.
Ex
typedef struct
{
float real;
float imag;
}complex;
complex u,v;
|
|
|
Slide 129 :
|
Structure and pointer It is possible to create a pointer to structures.
General format of declaring pointer to structure is
struct structure-tag-name { data type member1; data type member2; … … } *ptr;
Or
struct structure-tag-name { data type member1; data type member2; … … } ;
struct structure_tag-name *ptr;
|
|
|
Slide 130 :
|
struct book
{
char name[25] ;
char author[25] ;
int callno ;
} ;
struct book *ptr ;
An individual structure member can be accessed in terms of its corresponding pointer variable by writing
ptr- >member
Or
(*ptr).member
The -> operator can be combined with the period operator to access a submember within a structure
ptvar- >member. submember |
|
|
Slide 131 :
|
To initialize the structure members through pointer to structure we can use
(*ptr).member=constant;
Or
Ptr->member=constant;
Ex:
ptr->callno= 100; ptr->name = "Angelina"; |
|
|
Slide 132 :
|
struct invent
{
char *name[20];
int number;
float price;
};
void main()
{
struct invent product[3], *ptr;
printf(“Enter product details\n");
for(ptr = product; ptr < product+3; ptr++)
scanf("%s %d %f", ptr->name, &ptr->number, &ptr->price);
printf(“product details is ");
ptr = product;
while(ptr < product + 3)
{
printf("%-20s %5d %10.2f\n“,ptr->name,ptr->number,ptr->price);
ptr++;
}
} |
|
|
Slide 133 :
|
Passing structures to functions In two ways structure can be passed to function
Structure members can be transferred individually,
or Entire structures can be transferred
General format function prototype of passing structure to function is
Functionname(structure-variable-name);
|
|
|
Slide 134 :
|
struct employee
{
int emp_id;
char name[25];
char department[10];
float salary;
}empf;
main()
{
struct employee emp1=
{
12,
"sadanand",
"computer",
7500.00
};
display(emp1);
}
display(struct employee emp)
{
printf("%d %s %s %f", emp.emp_id,emp.name,emp.department,emp.salary);
} |
|
|
Slide 135 :
|
A complete structure can be transferred to a function by passing a structure-type pointer as an argument.
a structure passed in this manner will be passed by reference rather than by value. |
|
|
Slide 136 :
|
/* Passing address of a structure variable */
struct book
{
char name[25] ;
char author[25] ;
int pages ;
} ;
main( )
{
struct book b1 = { "Let us C", "YPK", 500 } ;
display ( &b1 ) ;
}
display ( struct book *b )
{
printf ( "\n%s %s %d", b->name, b->author, b->pages ) ;
} |
|
|
Slide 137 :
|
STRUCTURES AS FUNCTION PARAMETERS
Program
/* Passing a copy of the entire structure */
struct stores
{
char name[20];
float price;
int quantity;
};
struct stores update (struct stores product, float p, int q);
float mul (struct stores stock);
main()
{
float p_increment, value;
int q_increment;
struct stores item = {"XYZ", 25.75, 12};
printf("\nInput increment values:");
printf(" price increment and quantity increment\n");
scanf("%f %d", &p_increment, &q_increment);
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
item = update(item, p_increment, q_increment);
|
|
|
Slide 138 :
|
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
printf("Updated values of item\n\n");
printf("Name : %s\n",item.name);
printf("Price : %f\n",item.price);
printf("Quantity : %d\n",item.quantity);
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
value = mul(item);
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
printf("\nValue of the item = %f\n", value);
}
struct stores update(struct stores product, float p, int q)
{
product.price += p;
product.quantity += q;
return(product);
}
float mul(struct stores stock)
{
return(stock.price * stock.quantity);
}
|
|
|
Slide 139 :
|
Output
Input increment values: price increment and quantity increment
10 12
Updated values of item
Name : XYZ
Price : 35.750000
Quantity : 24
Value of the item = 858.000000 |
|
|
Slide 140 :
|
Self referencial structure structures which contain a member field pointing to the same structure type are called self-referential structures.
A self referential structure is used to create data structures like linked lists, stacks, etc
General form is
struct tag {
member 1;
member 2;
. . . . .
struct tag *name;
};
where name refers to the name of a pointer variable. |
|
|
Slide 141 :
|
EX:
struct node {
char item[10];
struct node *next;
};
In linklist each node contain 2 fields
One containing the data item(s).
The other containing the address of the next item in the list (that is, a pointer).
|
|
|
Slide 142 :
|
union A union, is a collection of variables of different types, just like a structure.
the members within a union all share the same storage area within the computer’s memory, whereas each member within a structure is assigned its own unique storage area.
At any given time Only one member of union may actually reside in the storage.so Only ONE member of each union can be referenced at a time
Declaring a union is exactly the same as declaring a struct, except you use the union keyword:
|
|
|
Slide 143 :
|
Union tag {
member 1 ;
member 2;
. . . . .
member m;
}var1,var2,…………;
EX:
union item { int m; float x; char c; } code;
|
|
|
Slide 144 :
|
we can use the same syntax for accessing union members that we use to access structure members.
Variablename.member-name
code.m=456;
The notation for accessing a union member that is nested inside a structure remains the same as for the nested structure.
|
|
|
Slide 145 :
|
Fig:Memory allocation for union |
|
|
Slide 146 :
|
structure Vs union |
|
|
Slide 147 :
|
Operations on union The following operations are valid on union
A union variable can be assigned to another union variable
Union variable can be passed to function as parameter
Address of a union variable can be extracted by using & operator
A function can accept and return a union or pointer to function
Donn’t perform arithmetic or logical operation on union variables
Donn’t try to initialize the more than the first union member
|
|