Class 4 Notes
Class 4 Notes
The above are the few examples of pointer declarations. If you need a
pointer to store the address of integer variable then the data type of
the pointer should be int. Same case is with the other data types.
& operator is also known as “Address of” Operator.
int main ()
{
return 0;
}
Let’s assume that we need to add 1 to the variable a. We can do this with
any of the following statements, assuming that the pointer p is initialized
p=&a,
#include <stdio.h>
int main () {
p=&a;
q=&a;
r=&a;
return 0;
}
Accessing multiple variable values with one pointer:
#include <stdio.h>
int main () {
p=&a;
printf("a values with p %d\n", *p );
p=&b;
printf("b values with p %d\n", *p );
return 0;
}
Pointers as arguments to functions
We can pass data to the called function and we also can pass
address(pointers). To pass addresses the formal parameters in the called
function are defined as a pointer to variables.
Call by value essentially means that a copy of the variable is passed into
the function. The function does not modify the original. Pass
by reference means that essentially the variable address is passed (though
the name may change).
#include <stdio.h>
OUTPUT
======
n1: 10, n2: 20
Example using Call by Reference
#include <stdio.h>
void swapByReference(int*, int*); /* Prototype */
OUTPUT
======
n1: 20, n2: 10
Function returning a pointer
void main()
{
int a,b,*ip;
scanf(“%d%d”,&a,&b);
ip=smaller(&a,&b);
printf(“\n smaller value is %d”,*ip);
}
Pointer to pointer
#include <stdio.h>
int main()
{
int num=123;
return 0;
}
Arrays and pointers
The following declaration defines an array of size 10, that is the block of
10 consecutive elements are a[0],a[1],a[2]...a[9]
int a[10];
Let us assume that an integer occupy 2 bytes of memory and base address
of array is 9700, so first value a[0] is at address 9700, next value a[1] is
at 9702, a[2] is at 9704 all elements of the array are located adjacent to
each other, if data elements are 5,10,15,..50 is shown as
#include<stdio.h>
void main()
{
int a[10],*pa,i,n=10,sum=0;
pa=a;
for(i=o;i<n;i++)
{
scanf(“%d”,pa+i);
}
for(i=o;i<n;i++)
{
sum=sum+*(pa+i));
}
printf(“\n %d”,sum);
}
Operations on pointers