In: Computer Science
Discuss what we mean by pointer arithmetic and give some examples.
Discuss the relationship between passing arrays to a function and using pointers to pass an array to a function.
a)
A pointer is a address in which a numeric value. Thusly, you can perform operations on a pointer similarly as you can on a numeric value. There are four arithmetic operators that can be utilized on pointers: ++, - , +, and -
ie, ptr++, ptr--, so on.
The pointer number-crunching or arithmetic is performed comparative with the base kind of the pointer. For instance, in the event that we have a number pointer IP which contains address 1000, at that point on incrementing it by 1, we will get 1004 (1000 + 1 * 4) rather than 1001 in light of the fact that the size of the int information type is 4 bytes. On the off chance that we had been utilizing a framework where the size of int is 2 bytes then we would get 1002 ( 1000 + 1 * 2 ).
b)
We can say that passing arrays to a function as using a call by value and using pointers to pass an array to a function as a call by reference.
call by value, the formal parameter or argument is replicated or dupication of the actual parameters.
that is, any change is done in the formal parameter doesnot affect actual parameter.
note that actual parameter are the argument used in the calling function and formal argument are the argument used in the called function. for better understanding for actual and formal argument, see the following example below.
In the call by reference, that is using pointer the formal parameter is the reference of the actual parameter that is any change is done in formal parameter can change the actual value.
Example for passing arrays to a function using call by value
#include <stdio.h>
void display( char chr) // chr is the formal argument // called
function
{
printf("%c ", chr);
}
int main()
{
char ar[] = {'h', 'e', 'l', 'l', 'o'};
for (int i=0; i<5; i++)
{
display (ar[i]); // ar[] is the actual argument // calling
function
}
return 0;
}
Example for using pointers to pass an array to a function
#include <stdio.h>
void display( int *number) // number is the formal argument //
called function
{
printf("%d ", *number);
}
int main()
{
int ar[] = {1, 2, 3, 4, 5};
for (int i=0; i<5; i++)
{
display (&ar[i]); // ar[] is the actual argument // calling
function
}
return 0;
}