UNIT IV FUNCTIONS AND POINTERS

158
UNIT IV FUNCTIONS AND POINTERS Function definition of function Declaration of function – Pass by value – Pass by reference – Recursion – Pointers - Definition Initialization Pointers arithmetic – Pointers and arrays- Example Problems.

description

UNIT IV FUNCTIONS AND POINTERS Function – definition of function – Declaration of function – Pass by value – Pass by reference – Recursion – Pointers - Definition – Initialization – Pointers arithmetic – Pointers and arrays- Example Problems. FUNCTION. - PowerPoint PPT Presentation

Transcript of UNIT IV FUNCTIONS AND POINTERS

Slide 1

UNIT IV FUNCTIONS AND POINTERS Function definition of function Declaration of function Pass by value Pass by reference Recursion Pointers - Definition Initialization Pointers arithmetic Pointers and arrays- Example Problems.FUNCTIONFunctions is a sub-program that contains one or more statements and it performs some task when called.TypesFunctionsUser-DefinedFunctions Pre-DefinedFunctions Pre-Defined Functions The pre-defined functions or library functions are built-in functions.The user can use the functions, but cannot modify the function.Example: sqrt()User-Defined Functions The functions defined by the user for their requirement are called user-defined functions.Whenever it is needed, The user can modify the function.Example: sum(a,b)

Advantage of User-Defined Functions The length of the source program can be reduced.It is easy to locate error.It avoid coding of repeated instructions.Elements of User-Defined FunctionFunction declarationFunction definitionFunction call

Function declaration

All the functions need to be declared before they are usedThe general form of function declaration is: [return_type]function_name([parameter_list or parameter_type_list])Example: int add (int ,int);

Return typeFunction nameparameter_type_listFunction DefinitionSyntax

datatype function_name (parameters list) {local variable declaration;body of the function;return(expression);}

How Function Works Once a function is called the control passes to the called function.The working of calling function is temporarily stopped.When the execution of called function is completed then the control return back to the calling function and execute the next statement.

ParametersActual ParameterThese are the parameters transferred from the calling function to the called function.Formal ParameterThese are the parameters which is used in the called function.

return StatementThe return statement may or may not send some values to the calling function.

Syntax:return; (or)return(expression); Function PrototypesFunction with no arguments and no return values.Function with arguments and no return values.Function with arguments and return values.Function with no arguments and with return values.

Function with no argumentsand no return valuesHere no data transfer take place between the calling function and the called function.These functions act independently, i.e. they get input and display output in the same block.

Example#include #includevoid main() //calling function{void add(void);add();}void add()//called function{ int a,b,c; printf("\nEnter two number:"); scanf("%d%d",&a,&b); c=a+b; printf("\nSum is:%d",c);}OutputEnter two number:34

Sum is:7

Function with argumentsand no return valuesHere data transfer take place between the calling function and the called function.It is a one way data communication, i.e. the called program receives data from calling program but it does not return any value to the calling program.

Example#include #includevoid main(){int a,b;void add(int,int);printf("\nEnter two number:");scanf("%d%d",&a,&b);add(a,b);}void add(int x,int y) //function with arguments{ int z; z=x+y; printf("\nSum is:%d",z);}OutputEnter two number:24

Sum is:6

Example#include #includevoid main(){int a,b;void add(int a,int b);printf("\nEnter two number:");scanf("%d%d",&a,&b);add(a,b);}void add(int x,int y) //function with arguments{ int z; z=x+y; printf("\nSum is:%d",z);}OutputEnter two number:24

Sum is:6

Function with argumentsand return valuesHere data transfer take place between the calling function and the called function as well as between called function and calling function .It is a two way data communication, i.e. the called program receives data from calling program and it return some value to the calling program.

Example#include #includevoid main(){int a,b,c;int add(int,int);printf("\nEnter two number:");scanf("%d%d",&a,&b);c=add(a,b);printf("\nSum is:%d",c);}int add(int x,int y){ int z; z=x+y; return(z);}OutputEnter two number:67

Sum is:13

Function with no argumentsand with return valuesHere data transfer take place between the called function and the calling function.It is a one way data communication, i.e. the called program does not receives data from calling program but it return some value to the calling program.

#include #includevoid main(){int add(),d;d=add();printf("\nSum is:%d",d);}int add() //function wit no argument{ int a,b,c; printf("\nEnter two number:"); scanf("%d%d",&a,&b); c=a+b; return(c);}OutputEnter two number:58

Sum is:13

Parameter Passing MethodsPass by valuePass by referencePass by valueActual argument passed to the formal argument.Any changes to the formal argument does not affect the actual argument.Example#include #includevoid main(){int x,y,change(int,int);printf("\nEnter value of x:");scanf("%d",&x);printf("\nEnter value of y:");scanf("%d",&y);

change(x,y);printf("\n\nValues in the Main()-->x=%d,y=%d",x,y);}int change(int a,int b){ int c; c=a; a=b; b=c; printf("\nValues in the Fuction -->x=%d,y=%d",a,b);}

OutputEnter value of x:5

Enter value of y:6

Values in the Fuction -->x=6,y=5

Values in the Main()-->x=5,y=6

Pass by referenceInstead of passing value, the address of the argument will be passed.Any changes to the formal argument will affect the actual argument.Example#include #includevoid main(){int x,y,change(int*,int*);printf("\nEnter value of x:");scanf("%d",&x);printf("\nEnter value of y:");scanf("%d",&y);change(&x,&y);printf("\n\nValues in the Main()-->x=%d,y=%d",x,y);}int change(int *a,int *b){ int c; c=*a;*a=*b; *b=c; printf("\nValues in the Function -->x=%d,y=%d",*a,*b);}

OutputEnter value of x:5

Enter value of y:6

Values in the Function -->x=6,y=5

Values in the Main()-->x=6,y=5

RecursionIt is a process of calling the same function itself again and again until some condition is satisfied.Syntax:func1(){..func1();}Example#include#includevoid main(){ int a; int rec(int); printf("\nEnter the number:"); scanf("%d",&a); printf("The factorial of %d! is %d",a,rec(a));}int rec(int x){ int f; if(x==1)return(1); elsef=x*rec(x-1); return(f);}

Output:Enter the number:5The factorial of 5! is 120

Example: Working of 3!

Library FunctionIt is pre-defined function.The library function provides functions like mathematical, string manipulation etc,.

Examplesqrt(x):It is used to find the square root of xExample: sqrt(36) is 6abs(x):It is used to find the absolute value of xExample: abs(-36) is 36pow(x,y):It is used to find the value of xyExample: pow(5,2) is 25ceil(x):It is used to find the smallest integer greater than or equal to xExample: ceil(7.7) is 8

rand():It is used to generate a random number.sin(x):It is used to find the sine value of xExample: sin(30) is 0.5cos(x): It is used to find the cosine value of xExample: cos(30) is 0.86tan(x): It is used to find the tan value of xExample: tan(30) is 0.577

toascii(x):It is used to find the ASCII value of xExample: toascii(a) is 97toupper(x):It is used to convert lowercase character to uppercase.Example: toupper(a) is A toupper(97) is Atolower(x):It is used to convert uppercase character to lowercase.Example: tolower(A) is a

Example:#include#include#include#includevoid main(){ int x,y=2; printf("\nEnter the number:"); scanf("%d",&x); printf("\nThe squareroot of %d is %f",x,sqrt(x));printf("\nThe value of %d power%dis%f ",x,y,pow(6,2)); printf("\nThe ceiling of 6.7 is %f",ceil(6.7)); printf("\nThe floor of 6.7 is %f",floor(6.7)); printf("\nThe absolute value of -6 is %d",abs(-6)); printf("\nThe value of sin 45 is %f",sin(45)); printf("\nThe uppercase of 'a' is %c",toupper('a')); printf("\nThe uppercase of 97 is %c",toupper(97)); getch();}

Output:Enter the number:6

The squareroot of 6 is 2.449490The value of 6 power 2 is 36.000000The ceiling of 6.7 is 7.000000The floor of 6.7 is 6.000000The absolute value of -6 is 6The value of sin 45 is 0.850904The uppercase of 'a' is AThe uppercase of 97 is A

PointersPointer is a variable that contains the memory address of another variable.Example:int x=5;

x Variable 1002 Address5ValueExample#include#includevoid main(){ int x=5; printf("\n The Address of x = %u",&x); printf("\n The Value of x = %d",x);}

OutputThe Address of x = 8714The Value of x = 5Pointer DeclarationSyntaxdata-type *pointer-name;data-type - Type of the data to which the pointer points.pointer-name - Name of the pointer

Example: int *a;Accessing Variable through PointerIf a pointer is declared and assigned to a variable, then the variable can be accessed through the pointer.

Example:int *a;x=5;a=&x; Example

#include#includevoid main(){ int x=5; int *a; a=&x; printf("\n The Value of x = %d",x); printf("\n The Address of x = %u",&x); printf("\n The Value of a = %d",a); printf("\n The Value of x = %d",*a);}

Output The Value of x = 5 The Address of x = 8758 The Value of a = 8758 The Value of x = 5

Example:#include#includevoid main(){ int y=10; int *a; a=&y; printf("\n The Value of y = %d",y); printf("\n The Address of y = %u",&y); printf("\n The Value of a = %d",a); printf("\n The Address of a = %u",&a);}5001108000ay5001VariableValueAddressOutputThe Value of y = 10The Address of y = 5001The Value of a = 5001The Address of a = 8000

Null PointerA pointer is said to be null pointer if zero is assigned to the pointer.

Exampleint *a,*b;a=b=0;Pointer to PointerHere one pointer stores the address of another pointer variable.

Example:int x=10,*a,**b;a=&x;b=&a;5001108000ax5001VariableValueAddress80009000bExample#include#includevoid main(){ int a=10; int *b,**c; b=&a; c=&b; printf("\n The Value of a = %d",a); printf("\n The Address of a = %u",&a); printf("\n The Value of b = %d",b); printf("\n The Address of b = %u",&b); printf("\n The Value of c = %d",c); printf("\n The Address of c = %u",&c);}

Output The Value of a = 10 The Address of a = 5001 The Value of b = 5001 The Address of b = 8000 The Value of c = 8000 The Address of c = 9000

Pointer ArithmeticSince a pointer is just a memory address, we can add to it to traverse an array.ptr+1 will return a pointer to the next array element. *ptr+1 vs. *ptr++ vs. *(ptr+1) ?What if we have an array of large structs (objects)?C takes care of it: In reality, ptr+1 doesnt add 1 to the memory address, but rather adds the size of the array element.69*ptr++ x = *p ; p = p + 1;

Pointer Arithmetic Summaryx = *(p+1) ? x = *(p+1) ; x = *p+1 ? x = (*p) + 1 ;x = (*p)++ ? x = *p ; *p = *p + 1;x = *p++ ? (*p++) ? *(p)++ ? *(p++) ? x = *p ; p = p + 1;x = *++p ? p = p + 1 ; x = *p ; Lesson?Using anything but the standard *p++ , (*p)++ causes more problems than it solves!int get(int array[], int n){ return (array[n]);// OR... return *(array + n);}Pointer ArithmeticC knows the size of the thing a pointer points to every addition or subtraction moves that many bytes.1 byte for a char, 4 bytes for an int, etc.So the following are equivalent:Pointer Arithmetic Question#invalid 1 2 3 4 5 6 7 8 9(1)0How many of the following are invalid?pointer + integer (ptr+1)integer + pointer (1+ptr)pointer + pointer (ptr + ptr)pointer integer (ptr 1_integer pointer (1 ptr)pointer pointer (ptr ptr)compare pointer to pointer (ptr == ptr)compare pointer to integer (1 == ptr)compare pointer to 0 (ptr == NULL)compare pointer to NULL (ptr == NULL)See following answer slideHow many of the following are invalid?pointer + integer (ptr+1)integer + pointer (1+ptr)pointer + pointer (ptr + ptr)pointer integer (ptr 1_integer pointer (1 ptr)pointer pointer (ptr ptr)compare pointer to pointer (ptr == ptr)compare pointer to integer (1 == ptr)compare pointer to 0 (ptr == NULL)compare pointer to NULL (ptr == NULL)Pointer Arithmetic Instruction Answer#invalid 1 2 3 4 5 6 7 8 9(1)03 are invalid (answers above)Pointers and FunctionsCall by ValueCall by ReferenceCall by valueActual argument passed to the formal argument.Any changes to the formal argument does not affect the actual argument.Example#include #includevoid main(){int x,y,swap(int,int);printf("\nEnter value of x:");scanf("%d",&x);printf("\nEnter value of y:");scanf("%d",&y);

change(x,y);printf("\n\nValues in the Main()-->x=%d,y=%d",x,y);}int swap(int a,int b){ int c; c=a; a=b; b=c; printf("\nValues in the Function -->x=%d,y=%d",a,b);}

OutputEnter value of x:5

Enter value of y:6

Values in the Function -->x=6,y=5

Values in the Main()-->x=5,y=6

79Pointer Arithmetic and ArraysBesides indexing, programmers use another powerful method of moving through an array: pointer arithmetic. Pointer arithmetic offers a restricted set of arithmetic operators for manipulating the addresses in pointers. Pointers and One-Dimensional ArraysArithmetic Operations on PointersUsing Pointer ArithmeticPointers and Two-Dimensional ArraysTopics discussed in this section:80Given pointer, p, p n is a pointer to the value n elements away.Note81FIGURE 10-5 Pointer Arithmetic

82Notea + n * (sizeof (one element)) a + n83FIGURE 10-6 Pointer Arithmetic and Different Types

84FIGURE 10-7 Dereferencing Array Pointers

85The following expressions are identical.*(a + n) and a[n]Note86

Table 10-1Pointers and Relational Operators87FIGURE 10-8 (Part I) Find Smallest

88FIGURE 10-8 (Part II) Find Smallest

89PROGRAM 10-1Print Array with Pointers

90PROGRAM 10-1Print Array with Pointers

91FIGURE 10-9 Pointers to Two-dimensional Arrays

92We recommend index notation for two-dimensional arrays.Note93 Passing an Array to a FunctionNow that we have discovered that the name of an array is actually a pointer to the first element, we can send the array name to a function for processing. When we pass the array, we do not use the address operator. Remember, the array name is a pointer constant, so the name is already the address of the first element in the array.94FIGURE:- Variables for Multiply Array Elements By 2

95PROGRAMMultiply Array Elements by 2

96PROGRAMMultiply Array Elements by 2

97PROGRAMMultiply Array Elements by 2

98PROGRAM Multiply Array Elements by 2

99

100 Memory Allocation FunctionsC gives us two choices when we want to reserve memory locations for an object: static allocation and dynamic allocation. Memory UsageStatic Memory AllocationDynamic Memory AllocationMemory Allocation FunctionsReleasing Memory (free)Topics discussed in this section:101FIGURE Memory Allocation

102FIGURE A Conceptual View of Memory

103We can refer to memory allocated in the heap only through a pointer.Note104FIGURE Accessing Dynamic Memory

105FIGURE Memory Management Functions

106Memory Allocation CastingPrior to C99, it was necessary to cast the pointer returned from a memory allocation function. While it is no longer necessary, it does no harm as long as the cast is correct.If you should be working with an earlier standard, the casting format is: pointer = (type*) malloc(size)Note107FIGURE malloc

108FIGURE calloc

109FIGURE realloc

110FIGURE Freeing Memory

111Using a pointer after its memory has been released is a common programming error. Guard against it by clearing the pointer.Note112The pointer used to free memory must be of the same type as the pointer used to allocate the memory.Note113Array of PointersAnother useful structure that uses arrays and pointers is an array of pointers. This structure is especially helpful when the number of elements in the array is variable.TableA Ragged Table

FIGURE A Ragged Array

Computer Memory RevisitedComputers store data in memory slotsEach slot has an unique addressVariables store their values like this:116AddrContentAddrContentAddrContentAddrContent1000i: 371001j: 461002k: 581003m: 741004a[0]: a1005a[1]: b1006a[2]: c1007a[3]: \01008ptr: 1001100910101011Computer Memory RevisitedAltering the value of a variable is indeed changing the content of the memorye.g. i = 40; a[2] = z;117AddrContentAddrContentAddrContentAddrContent1000i: 401001j: 461002k: 581003m: 741004a[0]: a1005a[1]: b1006a[2]: z1007a[3]: \01008ptr: 1001100910101011117Is there any questions so far?Addressing ConceptPointer stores the address of another entityIt refers to a memory location118int i = 5;int *ptr; /* declare a pointer variable */ptr = &i; /* store address-of i to ptr */printf(*ptr = %d\n, *ptr); /* refer to referee of ptr */118As its name suggests, Syntactically, a pointer variable is declared as a type identifier followed by an asterisk *.Why do we need Pointer?Simply because its there!It is used in some circumstances in C119Remember this?scanf(%d, &i);

119In fact, pointers are commonly encountered elements in C. Do you remember the simple but mysterious good old friend scanf() statement when you learnt the standard I/O facilities in C?What actually ptr is?ptr is a variable storing an addressptr is NOT storing the actual value of i120int i = 5;int *ptr;ptr = &i;printf(i = %d\n, i);printf(*ptr = %d\n, *ptr);printf(ptr = %p\n, ptr);5iaddress of iptrOutput:i = 5*ptr = 5ptr = effff5e0value of ptr = address of iin memory120This code segment appeared in the appetizer.Twin Operators&: Address-of operatorGet the address of an entitye.g. ptr = &j;121AddrContentAddrContentAddrContentAddrContent1000i: 401001j: 331002k: 581003m: 741004ptr: 1001100510061007Twin Operators*: De-reference operatorRefer to the content of the refereee.g. *ptr = 99;122AddrContentAddrContentAddrContentAddrContent1000i: 401001j: 991002k: 581003m: 741004ptr: 1001100510061007Example: Pass by ReferenceModify behaviour in argument passing123void f(int j){ j = 5;}void g(){ int i = 3; f(i);}void f(int *ptr){ *ptr = 5;}void g(){ int i = 3; f(&i);}i = ?i = ?i = 3i = 5123The program segment on the left is demonstrating pass by value, i.e. the value, actually a copy, of the variable i is passed as argument to function f(). The other program shows you pass by reference. The address of the variable i is passed to f() instead, thus allowing us to modify the content stored in the variable.An Illustration124int i = 5, j = 10;int *ptr; int **pptr; ptr = &i; pptr = &ptr; *ptr = 3;**pptr = 7;ptr = &j;**pptr = 9;*pptr = &i;*ptr = -2;Data TableNameTypeDescriptionValueiintinteger variable5jintinteger variable10An Illustration125int i = 5, j = 10;int *ptr; /* declare a pointer-to-integer variable */int **pptr; ptr = &i; pptr = &ptr; *ptr = 3;**pptr = 7;ptr = &j;**pptr = 9;*pptr = &i;*ptr = -2;Data TableNameTypeDescriptionValueiintinteger variable5jintinteger variable10ptrint *integer pointer variableAn Illustration126int i = 5, j = 10;int *ptr; int **pptr; /* declare a pointer-to-pointer-to-integer variable */ptr = &i; pptr = &ptr; *ptr = 3;**pptr = 7;ptr = &j;**pptr = 9;*pptr = &i;*ptr = -2;Data TableNameTypeDescriptionValueiintinteger variable5jintinteger variable10ptrint *integer pointer variablepptrint **integer pointer pointer variableDouble IndirectionAn Illustration127int i = 5, j = 10;int *ptr; int **pptr; ptr = &i; /* store address-of i to ptr */pptr = &ptr; *ptr = 3;**pptr = 7;ptr = &j;**pptr = 9;*pptr = &i;*ptr = -2;Data TableNameTypeDescriptionValueiintinteger variable5jintinteger variable10ptrint *integer pointer variableaddress of ipptrint **integer pointer pointer variable*ptrintde-reference of ptr

5An Illustration128int i = 5, j = 10;int *ptr; int **pptr; ptr = &i; pptr = &ptr; /* store address-of ptr to pptr */*ptr = 3;**pptr = 7;ptr = &j;**pptr = 9;*pptr = &i;*ptr = -2;Data TableNameTypeDescriptionValueiintinteger variable5jintinteger variable10ptrint *integer pointer variableaddress of ipptrint **integer pointer pointer variableaddress of ptr*pptrint *de-reference of pptrvalue of ptr(address of i)An Illustration129int i = 5, j = 10;int *ptr; int **pptr; ptr = &i; pptr = &ptr; *ptr = 3;**pptr = 7;ptr = &j;**pptr = 9;*pptr = &i;*ptr = -2;Data TableNameTypeDescriptionValueiintinteger variable3jintinteger variable10ptrint *integer pointer variableaddress of ipptrint **integer pointer pointer variableaddress of ptr*ptrintde-reference of ptr

3An Illustration130int i = 5, j = 10;int *ptr; int **pptr; ptr = &i; pptr = &ptr; *ptr = 3;**pptr = 7;ptr = &j;**pptr = 9;*pptr = &i;*ptr = -2;Data TableNameTypeDescriptionValueiintinteger variable7jintinteger variable10ptrint *integer pointer variableaddress of ipptrint **integer pointer pointer variableaddress of ptr**pptrintde-reference of de-reference of pptr7

An Illustration131int i = 5, j = 10;int *ptr; int **pptr; ptr = &i; pptr = &ptr; *ptr = 3;**pptr = 7;ptr = &j;**pptr = 9;*pptr = &i;*ptr = -2;Data TableNameTypeDescriptionValueiintinteger variable7jintinteger variable10ptrint *integer pointer variableaddress of jpptrint **integer pointer pointer variableaddress of ptr*ptrintde-reference of ptr

10An Illustration132int i = 5, j = 10;int *ptr; int **pptr; ptr = &i; pptr = &ptr; *ptr = 3;**pptr = 7;ptr = &j;**pptr = 9;*pptr = &i;*ptr = -2;Data TableNameTypeDescriptionValueiintinteger variable7jintinteger variable9ptrint *integer pointer variableaddress of jpptrint **integer pointer pointer variableaddress of ptr**pptrintde-reference of de-reference of pptr9

An Illustration133int i = 5, j = 10;int *ptr; int **pptr; ptr = &i; pptr = &ptr; *ptr = 3;**pptr = 7;ptr = &j;**pptr = 9;*pptr = &i;*ptr = -2;Data TableNameTypeDescriptionValueiintinteger variable7jintinteger variable9ptrint *integer pointer variableaddress of ipptrint **integer pointer pointer variableaddress of ptr*pptrint *de-reference of pptrvalue of ptr(address of i)133An Illustration134int i = 5, j = 10;int *ptr; int **pptr; ptr = &i; pptr = &ptr; *ptr = 3;**pptr = 7;ptr = &j;**pptr = 9;*pptr = &i;*ptr = -2;Data TableNameTypeDescriptionValueiintinteger variable-2jintinteger variable9ptrint *integer pointer variableaddress of ipptrint **integer pointer pointer variableaddress of ptr*ptrintde-reference of ptr

-2Pointer ArithmeticWhats ptr + 1? The next memory location!Whats ptr - 1? The previous memory location!Whats ptr * 2 and ptr / 2?Invalid operations!!!135Pointer Arithmetic and Array136float a[4];float *ptr;ptr = &(a[2]);*ptr = 3.14;ptr++;*ptr = 9.0;ptr = ptr - 3;*ptr = 6.0;ptr += 2;*ptr = 7.0;Data TableNameTypeDescriptionValuea[0]floatfloat array element (variable)?a[1]floatfloat array element (variable)?a[2]floatfloat array element (variable)?a[3]floatfloat array element (variable)?ptrfloat *float pointer variable*ptrfloatde-reference of float pointer variable?Pointer Arithmetic and Array137float a[4];float *ptr;ptr = &(a[2]);*ptr = 3.14;ptr++;*ptr = 9.0;ptr = ptr - 3;*ptr = 6.0;ptr += 2;*ptr = 7.0;Data TableNameTypeDescriptionValuea[0]floatfloat array element (variable)?a[1]floatfloat array element (variable)?a[2]floatfloat array element (variable)?a[3]floatfloat array element (variable)?ptrfloat *float pointer variableaddress of a[2]*ptrfloatde-reference of float pointer variable?Pointer Arithmetic and Array138float a[4];float *ptr;ptr = &(a[2]);*ptr = 3.14;ptr++;*ptr = 9.0;ptr = ptr - 3;*ptr = 6.0;ptr += 2;*ptr = 7.0;Data TableNameTypeDescriptionValuea[0]floatfloat array element (variable)?a[1]floatfloat array element (variable)?a[2]floatfloat array element (variable)3.14a[3]floatfloat array element (variable)?ptrfloat *float pointer variableaddress of a[2]*ptrfloatde-reference of float pointer variable3.14Pointer Arithmetic and Array139float a[4];float *ptr;ptr = &(a[2]);*ptr = 3.14;ptr++;*ptr = 9.0;ptr = ptr - 3;*ptr = 6.0;ptr += 2;*ptr = 7.0;Data TableNameTypeDescriptionValuea[0]floatfloat array element (variable)?a[1]floatfloat array element (variable)?a[2]floatfloat array element (variable)3.14a[3]floatfloat array element (variable)?ptrfloat *float pointer variableaddress of a[3]*ptrfloatde-reference of float pointer variable?Pointer Arithmetic and Array140float a[4];float *ptr;ptr = &(a[2]);*ptr = 3.14;ptr++;*ptr = 9.0;ptr = ptr - 3;*ptr = 6.0;ptr += 2;*ptr = 7.0;Data TableNameTypeDescriptionValuea[0]floatfloat array element (variable)?a[1]floatfloat array element (variable)?a[2]floatfloat array element (variable)3.14a[3]floatfloat array element (variable)9.0ptrfloat *float pointer variableaddress of a[3]*ptrfloatde-reference of float pointer variable9.0Pointer Arithmetic and Array141float a[4];float *ptr;ptr = &(a[2]);*ptr = 3.14;ptr++;*ptr = 9.0;ptr = ptr - 3;*ptr = 6.0;ptr += 2;*ptr = 7.0;Data TableNameTypeDescriptionValuea[0]floatfloat array element (variable)?a[1]floatfloat array element (variable)?a[2]floatfloat array element (variable)3.14a[3]floatfloat array element (variable)9.0ptrfloat *float pointer variableaddress of a[0]*ptrfloatde-reference of float pointer variable?Pointer Arithmetic and Array142float a[4];float *ptr;ptr = &(a[2]);*ptr = 3.14;ptr++;*ptr = 9.0;ptr = ptr - 3;*ptr = 6.0;ptr += 2;*ptr = 7.0;Data TableNameTypeDescriptionValuea[0]floatfloat array element (variable)6.0a[1]floatfloat array element (variable)?a[2]floatfloat array element (variable)3.14a[3]floatfloat array element (variable)9.0ptrfloat *float pointer variableaddress of a[0]*ptrfloatde-reference of float pointer variable6.0Pointer Arithmetic and Array143float a[4];float *ptr;ptr = &(a[2]);*ptr = 3.14;ptr++;*ptr = 9.0;ptr = ptr - 3;*ptr = 6.0;ptr += 2;*ptr = 7.0;Data TableNameTypeDescriptionValuea[0]floatfloat array element (variable)6.0a[1]floatfloat array element (variable)?a[2]floatfloat array element (variable)3.14a[3]floatfloat array element (variable)9.0ptrfloat *float pointer variableaddress of a[2]*ptrfloatde-reference of float pointer variable3.14Pointer Arithmetic and Array144float a[4];float *ptr;ptr = &(a[2]);*ptr = 3.14;ptr++;*ptr = 9.0;ptr = ptr - 3;*ptr = 6.0;ptr += 2;*ptr = 7.0;Data TableNameTypeDescriptionValuea[0]floatfloat array element (variable)6.0a[1]floatfloat array element (variable)?a[2]floatfloat array element (variable)7.0a[3]floatfloat array element (variable)9.0ptrfloat *float pointer variableaddress of a[2]*ptrfloatde-reference of float pointer variable7.0Pointer Arithmetic and Arrayfloat a[4];float *ptr;ptr = &(a[2]);*ptr = 3.14;ptr++;*ptr = 9.0;ptr = ptr - 3;*ptr = 6.0;ptr += 2;*ptr = 7.0;Type of a is float *a[2] *(a + 2)ptr = &(a[2])ptr = &(*(a + 2))ptr = a + 2a is a memory address constantptr is a pointer variable145More Pointer ArithmeticWhat if a is a double array?A double may occupy more memory slots!Given double *ptr = a;Whats ptr + 1 then?146AddrContentAddrContentAddrContentAddrContent1000a[0]: 37.91001100210031004a[1]: 1.231005100610071008a[2]: 3.14100910101011More Pointer ArithmeticArithmetic operators + and auto-adjust the address offsetAccording to the type of the pointer:1000 + sizeof(double) = 1000 + 4 = 1004147AddrContentAddrContentAddrContentAddrContent1000a[0]: 37.91001100210031004a[1]: 1.231005100610071008a[2]: 3.14100910101011Advice and PrecautionProsEfficiencyConvenienceConsError-proneDifficult to debug148SummaryA pointer stores the address (memory location) of another entityAddress-of operator (&) gets the address of an entityDe-reference operator (*) makes a reference to the referee of a pointerPointer and arrayPointer arithmetic149Pointer to ArrayThe elements of the array can also be accessed through a pointer.

Exampleint a[3]={2,3,7};int *b;b=a;Example:#include#includevoid main(){ int a[3]={2,3,7}; int *b; b=a; printf("\n The Value of a[0] = %d",a[0]); printf("\n The Address of a[0] = %u",&a[0]); printf("\n The Value of b = %d",b);}

874429000ba[0]8744VariableValueAddressOutputThe Value of a[0] = 2 The Address of a[0] = 8744 The Value of b = 8744

Example#include#includevoid main(){ int a[5]={2,3,7,9,10}; int i; for(i=0;i