Documente Academic
Documente Profesional
Documente Cultură
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
5/3/12
POINTERS
a
address that can be used to access that location so a pointer variable points to a
5/3/12
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
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
5/3/12
5/3/12
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
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
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
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
5/3/12
PROGRAM
5/3/12
PROGRAM
5/3/12
18
5/3/12
19
5/3/12
PROGRAM 93
5/3/12
21
PROGRAM 93
5/3/12
22
5/3/12
The
void pointers
5/3/12
pointer.
void For
example
Null pointer
Anull
5/3/12
memory address.
NULL
5/3/12
The
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.
5/3/12
pointer is passed to a function), the address of a data item is passed to the function.
When
function declaration does not include variable names, the data type of each pointer argument must be followed by an asterisk.
5/3/12
5/3/12
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
5/3/12
element, the address of the first element and the name of the array both represent the same location in memory
Name
5/3/12
5/3/12
Not e
same a
5/3/12
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
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.
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
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
5/3/12
&operator
&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
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
5/3/12
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
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.
5/3/12
Storage of C program
48 48
5/3/12
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
size_t is defined in header file as unsigned integer Size is the amount of memory we wish to allocate
The
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.
5/3/12
5/3/12
element_size);
Allocate initialize return
allocate block
The
ptr=(cast-type*) calloc(n,elem-size);
The
*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.
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.
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
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);
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
5/3/12
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]
*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
i:30
5/3/12
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
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
i 3 64 85 k 327 723 6 4
5/3/12
Example
5/3/12
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
5/3/12
g s
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
array of pointers.
In
such situations the newly defined array will have one less
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 ) ) ;
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
5/3/12
5/3/12
5/3/12
An
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
5/3/12
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" ) ;
5/3/12
Pointers to function
A
5/3/12
name in parentheses.
General
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.
5/3/12
address of a function in your program. #include <stdio.h> void (*foo)(int); void myfunc(int x) { printf( "%d\n", x ); } void main()
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 );
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
5/3/12
returns the next argument in the list, cleans up the variable argument list.
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_arg takes a va_list and a variable type, and returns the next
#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
5/3/12
an argument.
We
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.
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.
5/3/12
5/3/12
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
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
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
Ex: struct student { char *name; int rollno; float totalmark; } stud1={"Ashraf",1,98}; main() { struct student stud2={"Rahul",3,97}; .. }
q
5/3/12
the system . For integer and float default value is 0 and char and string type members the default value is \0;
111 111
5/3/12
5/3/12
Processing of structure
Click to edit Master subtitle style
5/3/12
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
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
5/3/12
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
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
5/3/12
Arrays of structure can be initialized in the same way as arrays General form struct structure-name { datatype member1; . .
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
5/3/12
5/3/12
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
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
5/3/12
General
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
5/3/12
To
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++; } }
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
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
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
5/3/12
One containing the data item(s). The other containing the address of the next item in the list (that is, a pointer).
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
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