POINTERS
5/3/12
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,
Click to edit Master subtitle style
pointers and variable length arguments list
passing functions to other functions.
5/3/12
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
5/3/12
A variable name directly references a value.
A pointer indirectly references a value. Referencing a value through a pointer is called indirection. A variables address is the first byte occupied by the variable.
5/3/12
Why pointer needed
q q q
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
q q
5/3/12
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;
5/3/12
Pointer Variable Declaration
5/3/12
Declaring Pointer Variables
Address operator &
& -- "address operator" which gives the memory address of a variable Indirection operator*
5/3/12
Indirection operator also called Dereference operator
5/3/12
5/3/12
5/3/12
Placement of the indirection operator before a The value of a dereferenced pointer is not the
pointer is said to dereference the pointer.
q
address.it is the value of a variable that points to
m 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); }
i 3 64 85
j 64 85
5/3/12
6485 6485 3276 3 3 3
32 76
Initializing Pointers
5/3/12
Like other variables, always initialize pointers before using them!!! example: int x=3; int *p; printf("%d",p); /*donnt*/ p = &x; printf("%d",*p); /* Correct */
For
int main(){
5/3/12
Initializing Pointer Variables
5/3/12
q 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
q Any number of pointer can point to same address
int a; int *p,*q,*r; p=&a; q=&a; r=&a;
5/3/12
One Variable with Many Pointers
PROGRAM
Using A Variable with Many Pointers
5/3/12
PROGRAM
Using A Variable with Many Pointers
5/3/12
18
5/3/12
19
5/3/12
PROGRAM 93
Add Two Numbers Using Pointers
5/3/12
21
PROGRAM 93
Add Two Numbers Using Pointers
5/3/12
22
5/3/12
Add Two Numbers Using Pointers
The
void pointers
5/3/12
void type of pointer is a special type of
pointer.
void For
pointers can point to any data type
example
int a=5; void *vp; vp=&a;
Pointers to void cannot be directly
dereferenced like other pointer variables , by
Null pointer
Anull
5/3/12
pointeris 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 #defineNULL 0
We
can initialize a pointer to null pointer as
int*ptr=NULL; We can also use constant value 0 int *ptr=0;
5/3/12
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.
Passing pointers to function
When
5/3/12
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.
5/3/12
Returning more than 1 value from a function
A
5/3/12
function will return only 1 value at a time
when passing arguments by value.
using
pointers, function can return more
than 1 value #include<stdio.h> float areaperi(float,float *); void main() { float r,area,perimeter;
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.
5/3/12
pointers and one dimensional arrays
The
5/3/12
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
5/3/12
FIGURE Pointers to Arrays
5/3/12
Not e
same a
&a[0] a is a pointer only to the first element.
5/3/12
a+ printf(%u 1 a+2 %u,a,&a[0]); a+3 a+4
2147478270 2147478270
34 34
5/3/12
We can access array elements in different ways a[i] *(a+i); *(i+a); i[a]
5/3/12
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.
Passing array to function
When passing array to the function formal argument of the function may be
5/3/12
/* Demonstration of passing an array to a function int a[] or int *a */ 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] ) ; } }
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 */ passing the address of the zeroth element of the array to } } a function is as good as passing the entire array to the
5/3/12
function display(&num[0],6) is same as display(num,6);
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 cannt used as lvalue.but pointer used as l value main()ex: For { float a[5]; for(i=0;i<n;i++) { *a=0.0; a++; //error } } main() { float *ptr, a[5]; ptr=a; for(i=0;i<n;i++) { *ptr=0.0; ptr++; //ptr access a[i] }
5/3/12
5/3/12
Array
cannot be assigned to another but two pointer variable can be assigned
main() { int a[5]={1,2,3,4,5} int b[5]; b=a; //wrong } } main() { int a[5]={1,2,3,4,5} int *ptr1,*ptr2; ptr1=&a[0]; ptr2=ptr1;
5/3/12
&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 main() { main()
{ int a[]={1,2,3,4,5}; int a[]={1,2,3,4,5}; printf(%u%u int *ptr; %u,a,&a[0],&a); ptr=a; } printf(%u%u will print 65506 65506 65506 %u,&a[0],ptr,&ptr); Will print 65506 65506 65526
5/3/12
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 main() { int a[]={1,2,3,4,5}; int *ptr; ptr=a; printf(%d,sizeof(ptr)); Will print 2
main() { int a[]={1,2,3,4,5}; printf(%d,sizeof(a)); } will print 10
Difference between array and pointer
Arrays Arraysuse subscripted variables to access and manipulate data. pointers Pointersare used to manipulate data using the address. Pointers use * operator to access the data pointed to by them
5/3/12
Arrays automatically allocate pointers are dynamic. space which is fixed in size and location; It cannot be resized It cannot be reassigned It can be resized using realloc() It can be reassigned
sizeof(arrayname) gives sizeof(p) returns number of number of bytes occupied by bytes used to store the the array pointer variable p
Dynamic memory allocation
5/3/12
The process of allocating memory atcompile-time is
known as Static memory allocation The process of allocating memory at run time is known as dynamic memory allocation.
5/3/12
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
Memory allocation process
5/3/12
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 Cs dynamic allocation functions come from the heap: the region of free memory that lies between your programs permanent storage area and the stack.
FIGURE : A Conceptual View of
5/3/12
Storage of C program
FIGURE Accessing Dynamic Memory
48 48
5/3/12 Computer Science: A Structured Programming Approach Using C
5/3/12
Memory Management Functions
5/3/12
Function Task
malloc calloc realloc free used to allocate a single block of memory used to allocate multiple blocks of memory used to extend the amount of space allocated previously
used to tell program a piece of memory no longer needed These functions are defined in stdlib.h
malloc()
Prototype
5/3/12
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 bytesize.
If p is returning NULL then will terminate from the program
5/3/12
callo Protype c() : void *calloc(size_t num_elements, size_t
5/3/12
element_size);
Allocate initialize return
a block of num_elements * element_size bytes every byte to zero
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;
free()
With the dynamic runtime allocation, it is our responsibility to release the space when it is not required.
5/3/12
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
5/3/12
realloc()
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.
5/3/12
5/3/12
MEMSET() function
To
5/3/12
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);
Following operation is possible on pointers
operation on pointers (pointer arithmetic)
variable e.g., pv = &v).
A pointer variable can be assigned the address of an ordinary
A pointer variable can be assigned the value of another pointer
5/3/12
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
Cannt perform following operation on pointers
q
5/3/12
Addition of 2 pointers Multiplying a pointer with a number Division of pointer by number
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 p p+1 p+2 p+3 p+4 p+5 p+6 p+7
5/3/12
a[0] a[1]
a[2]
a[3]
a[4]
a[5]
a[6]
a[7] a[8] a[9]
*ptr++ q increments the pointer q equivalent to int temp; temp=ptr;ptr=ptr+1 q ++*ptr increment the value pointed by pointer q 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;
5/3/12
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);
5/3/12
Output *ptr=10 i:10 *ptr:20 i:20 *ptr=21
i:30
5/3/12
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
Comparison of two pointer variables
5/3/12
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
Pointers to pointers
5/3/12
a pointer which contains another pointers address 6485 327
6
i 3 64 85 k 327 723 6 4
main () { int i = 3 ; int * j ; int * * k ; //pointer to pointer to an integer
5/3/12
Example
pointers and multidimensional arrays,
5/3/12
A 2D array is actually a collection of 1D array.so we
can define a 2D array as a collection of 1D arrays.
Fig:Physical representation of 2 dimensional array a[3][2]
5/3/12
We know a[i] = *(a+i) .in same manner 2d array can be expressed as o a[i][j]= *(a[i]+j)=(*(a+i))[j]=*(*(a+i)+j)
o
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 )
5/3/12
pointers and strings
5/3/12
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
g s
o o d \0 s[0] s[1] s[2] s[3] s[4]
Second declaration tells the compiler allocate space in memory for ptr.puts the string constant good in memory and initialise g o o of \0 ptr with base addressd string constant. ptr
5/3/12
//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 ) ; }
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 */ }
5/3/12
5/3/12
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.
main( ) { char str1[ ] = "Hello" ; char *p = "Hello" ; str1 = "Bye" ; /* error */ p = "Bye" ; /* works */ }
array of pointers
an
5/3/12
array of pointers are collection of addresses. addresses present in the array of pointers can be
The
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 ;
5/3/12
5/3/12
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] ;
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.
5/3/12
5/3/12
#include <stdio.h>
5/3/12
#include <stdlib.h> #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 ) ) ;
readinput(a, nrows, ncols); readinput(b, nrows, ncols); computesums(
5/3/12
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] +col); return; }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) ; }
5/3/12
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", Here names[ ] is an array of pointers. It contains base addresses of respective names "gopal", "rajesh"
5/3/12
5/3/12
5/3/12
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.
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
pointer to an array
5/3/12
data- type ( *ptvar) [ expression 2] ; rather than data- type array[ expression I] [ expression 2];
/* Usage of pointer to an array */ main( ) { output is 65500 int a[][2] = { 65500 1,2, 65502 3,4, 65504 5,6, }; int *p; int (*q)[2]; //q is an pointer to an array of 2 integers
While passing 2d array to function we can use pointer to an array
5/3/12
Example void show(int ( *q )[4], int row, int col ); main( )
void show ( int ( *q )[4], int row, int col ) { { int a[3][4] = { int i, j ; 1, 2, 3, 4, int *p ; 5, 6, 7, 8, for ( i = 0 ; i < row ; i++ ) { 9, 0, 1, 6 p=q+i; }; for ( j = 0 ; j < col ; j++ ) printf ( "%d ", * ( p + j ) ) ; //same show ( a, 3, 4 ) ; } as //*(*(q+i)+j) printf ( "\n" ) ; } printf ( "\n" ) ;
Difference between array of pointer and pointer to an array
Array of pointer Pointer to an array Declaration: Declaration: Datatype *array-name[SIZE]; Datatype(*array-name)[SIZE]; Size means no:of rows Size represent no:of columns Space for columns are dynamically allocated Space for rows are dynamically allocated
5/3/12
Pointers to function
A
5/3/12
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 A
cannot perform pointer arithmetic on pointers to functions.
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, . . )
5/3/12
Consider the declarations int *f(int a); /* function f returning an int* */ int (*g)(int a); /* pointer g to a function returning an int*/
qIn the first declaration, f is interpreted as a function that takes an int as argument, and returns a pointer to an int. qIn the second declaration, g is interpreted as a pointer to a function that takes an int argument and that returns an int. q() 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.
Initializing Function Pointers
Like
5/3/12
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 <stdio.h> void (*foo)(int); void myfunc(int x) { printf( "%d\n", x ); } void main()
Calling a function using function pointer
5/3/12
to call the function pointed to by a function pointer, use the name of the function pointer EX:
#include <stdio.h> void (*foo)(int); void myfunc(int x) { printf( "%d\n", x ); } void main() { foo = myfunc; //To call myfunc foo( 2 );
Uses of pointers to function
5/3/12
In In In In
writing memory resident programs writing viruses or vaccines to remove the viruses developing COM/DCOM components VC++ programming to connect events to function
call
pointers and variable length arguments list
For
5/3/12
implementing variable number of arguments 3 macros
are availble in stdarg.hcalled va_start ,va_arg, va_end.
qva_start-which
initializes pointer to the beginning of the list
of optional arguments list,
qva_arg,-which qva_end-which
returns the next argument in the list, cleans up the variable argument list.
to use these macros , we need a variable capable of storing a
5/3/12
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.
#include <stdarg.h> #include <stdio.h> 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 ) ); }
5/3/12
PASSING FUNCTIONS TO OTHER FUNCTIONS
A
5/3/12
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.
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, . . . ) 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 .
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
5/3/12
function declaration for the host function. It may be written as funct- data- type funct-name( arg-data-type (*) ( type 1 , type 2, . . ), pointer to guest function data types of other funct args);
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 functions arguments.
5/3/12
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); }
5/3/12
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; {
5/3/12
5/3/12
STRUCTURE
and union
q
Defining a structure processing a structure user defined data types structure and pointers, passing structure to function, self-referential structures union.
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.
5/3/12
DEFINING A STRUCTURE
Declaring a structure requires the struct keyword, followed by a 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.
name. Then you declare your collection of members between a pair
5/3/12
5/3/12
Fig: Tagged Structure Format
qWe can declare structure variables as struct structure_name var1,var2, ..,var n; qSo we can declare structure variables stud1, stud2 as struct student stud1,stud2; qit is possible to combine the declaration of structure combination with that of the structure variables.
5/3/12
struct structure_name { type element 1; type element 2;
Ex: struct student
name[25]; totalmark; stud2; { int rollno; char float } stud1,
Structure type declaration doesnot tell compiler to reserve space
5/3/12
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
1.
2.
3.
struct Ex Variable structure can be defined as { struct memberlist { }variable int x; identifier; int y; }a;
5/3/12
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.
Initializing of Structure
Structure the
5/3/12
members can be initialized at declaration.
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 . general form is
The
struct stucture_name structure-variable={constant1,constant2,..};
struct structure_name or { type element1; .. }structure
Ex: struct student { char *name; int rollno; float totalmark; } stud1={"Ashraf",1,98}; main() { struct student stud2={"Rahul",3,97}; .. }
q
5/3/12
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;
FIGURE Initializing Structures
111 111
5/3/12
5/3/12
Processing of structure
Click to edit Master subtitle style
Accessing structure members
5/3/12
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
Example program for structure #include<stdio.h>
structstudent { charname[10]; floatmarks; }stud1,stud2; voidmain() { stud1.name="Tom"; stud2.marks=99.9; printf("Nameis%s\n",stud1.name); printf("Marksare%f\n",stud2.marks); }
5/3/12
//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
5/3/12
Copying and comparing structures
Structure
5/3/12
can be assigned to another structure of same type
Ex:
struct Student s1,s2; s1.name = "Joe "; s2 = s1; Copies the entire structure
How Structure Elements are Stored of a structure are always stored in contiguous memory elements
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 ) ;
5/3/12
Output Address of name = 65518 Address of price = 65519 Address of pages = 65523
5/3/12
Array of structures
5/3/12
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 structurevariable[index];
#include<stdio.h> #include<conio.h> 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<n;i++) { printf("\nEnter name,rollnumber and mark of %d student\n",i); scanf("%s%d
5/3/12
Initializing arrays of structures
5/3/12
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}, .
5/3/12
Example
structmarks { int subject1; int subject2; int subject3; }; struct marks student[3]= { { 45,68,81},{75,53,69}, {57,36,71} };
5/3/12
Nesting of structures
5/3/12
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 variable. member. submember Ex:
5/3/12
We can access members of inner structures as
5/3/12
User defined data types(typedef)
The
5/3/12
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 doesnt occupy storage :simply defines a new type Ex:
5/3/12
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;
Structure and pointer
It
5/3/12
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;
5/3/12
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 ptvar- >member. writing
submember
ptr- >member Or (*ptr).member
5/3/12
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";
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
5/3/12
ptr++; } }
Passing structures to functions
In
5/3/12
two ways structure can be passed to function members can be transferred individually,
Structure
or Entire structures can be transferred format function prototype of passing structure to function is
General
Functionname(structure-variable-name);
5/3/12
struct employee { int emp_id; char name[25]; char department[10]; float salary; }empf; main() { struct employee emp1= { 12, "sadanand", "computer", 7500.00 };
5/3/12
complete structure can be transferred to a function by passing a structure-type pointer as an argument. structure passed in this manner will be passed by reference rather than by value.
/* 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 ) ; }
5/3/12
display ( struct book *b )
STRUCTURES AS FUNCTION PARAMETERS Program /* Passing a copy of the entire structure */
5/3/12
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ 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); }
5/3/12
5/3/12
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
Self referencial structure
structures
5/3/12
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;
5/3/12
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).
A union, is a collection of variables of different types, just like a structure.
union
5/3/12
the members within a union all share the same storage area within the computers 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:
Union tag { member 1 ; member 2; ..... member m; }var1,var2,; EX: union item { int m; float x; char c; } code;
5/3/12
we can use the same syntax for accessing union members that we use to access structure members. Variablename.member-name
5/3/12
code.m=456;
The notation for accessing a union member that is nested inside a structure remains the same as for the nested structure.
5/3/12
Fig:Memory allocation for union
structure Vs union Structure
5/3/12
union
i.Member Access We can Only one member of union can be access all the members of structure accessed at anytime at anytime. ii. Memory Allocation-the amount Amount of memory required is size of memory required to store stucture of Largest member in union. is sum of the size of each because union members are overlaps member in the structure on each other in memory. iii. Initialization All members Only the first member of a union can of structure can be initialized be initialized. . iv. Keyword 'struct' keyword 'union' keyword is used to declare is used to declare structure. union. If we declare two structure variables ,Both variables are stored in different location Union variables are stored in same location.
5/3/12
Operations on union
The following operations are valid on union
1.
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 perform arithmetic or logical operation
2.
3.
4.
.Donnt