Pointers
Pointers
Chapter 9
Recall from function
Call by value & Call by reference ( Or Pass by value & Pass by reference)
An argument is a data passed from a program to the function. In function, we can pass
a variable by two ways.
int *a ;
float *b ;
char *c ;
where a, b, c are pointer variable which stores address of integer, float and char
variable.
Thus the following assignments are valid.
int x ;
float y ;
char c ;
a = &x ; /* the address of x is assigned to pointer variable a */
b = &y ; /* the address of y is stored to pointer variable b */
c = &c ; /* the address of c is stored to pointer variable c */
Before studying pointers, it is important to understand how memory is organized in a computer. The memory
in a computer is made up of bytes arranged in a sequential manner. Each byte has an index number which is
called address of that byte. The address of these bytes start from zero and the address of last byte is one less
than the size of memory. Suppose we have 64MB of RAM (Random Access Memory), then memory will
consist of 64×220= 67108864. the address of these bytes will be from 0 to 67108863.
We have studied that it is necessary to declare a variable before using it, since compiler has to
reserve space for it. The data type of the variable also has to be mentioned so that the compiler
knows how much space need to be reserved. For example:
int age;
The compiler reserves 2 consecutive bytes from memory for this variable and associates the
name age with it. The address of first byte from the two allocated bytes is k\a the address of
variable age.
Suppose compiler has reserved bytes numbered 65524 and 65525 for the storage of variable age,
then the address of variable age will e 65524. Let us assign some value to this variable.
age = 20;
Now this value will be stored in these 2 bytes in form of binary representation. The number of
bytes allocated will depend on the data type of variable. For example, 4 bytes would have been
allocated for a float variable, and the address of first byte would be called the address of
variable.
Address operator (&):
C provides an address operator ‘&’, which returns the address of a variable when
placed before it. This operator can be read as “the address of”, so ‘&sn’ means
address of sn, similarly ‘&price’ means address of price. The following program
prints the address of variables using address operator
/* Program to print address of variable using & */
#include<stdio.h>
main( )
int sn = 30;
output:
have some address. All pointers irrespective of their base type will occupy same space in
memory since all of them contain address only. Generally 2 bytes are used to store an address
(may vary in different computers), so the compiler allocates 2 bytes for a pointer variable.
If pointers are declare after the variable like
int sn=30,*p=sn;
float price=150.50,*q=&price;
It is also possible to assign the value of one poin ter variable to the other provided their base type is some.
P1=P;
Now, both pointer variable P and P1 contains the address of variable sn and points the same variable
Pointers (that is, pointer values) are generated with the ``address-of'' operator&,
which we can also think of as the``pointer-to'' operator. We demonstrate this by
declaring (and initializing) anintvariablei, and then settingiptopoint to it:
int i = 5; ip = &i;
The assignment expression ip = &i; contains both parts of the “two-step process'':
&i generates a pointer to i, andthe assignment operator assigns the new pointer to
(that is, places it ``in'') the variable ip. Now ip”points to''i,which we can illustrate
with this picture
Application of pointer:
Some uses of pointers are
1) Accessing array elements
2) Returning more than one value from a function
3) Accessing dynamically allocated memory
4) Implementing data structure like linked lists, trees, and graphs.
5) Increasing the execution speed as they refer address.
Indirection or Deference Operator:
In above program, if we place ‘*’ before P1
The operator ‘*’, used in front of a variable, is called when we can access the variable whose
pointer or indirection or deference operator. Normal address is stored in P1. Since P1 contains
variable provides direct access to their own values the address of variable a, we can access the
where as a pointer provides indirect access to the variable a by waiting *P1. Similarly we can
values of the variable whose address it stores. The access variable b by writing *P2. So we can
indirection operator (*) is used in two distinct ways use *P1 & *P2 in place of variable names a
with pointers, declaration and deference. When the and b anywhere in our program. Let us see
pointer is declared, the star indicates that it is a pointer,
some other examples:
not a normal variable. When the pointer is deferenced,
the indirection operator indicates the value at that *P1=9; is equivalent to a=9;
memory location stored in the pointer. Let us take an
example: (*P1)++; is equivalent to a++;
int a = 87; x=*P2+10; is equivalent to x=b+10;
float b = 4.5; printf(“%d %f”,*P1,*P2); is equivalent to
printf(“%d%f”,a,b);
int*P1 = &a;
scanf(“%d%f”,P1,P2); is equivalent to
float*p2 = &b;
scanf(“%d%f”,&a,&b);
#include<stdio.h>
OUTPUT:
main( ){
Value of P1 = Address of a = 65524
int a=50; Value of P2 = Address of b = 65520
Address of P1 = 65518
float b=4.5;
Address of P2 = 65516
int *P1=&a; Value of a = 50 50 50
Value of b = 4.500000 4.500000 4.500000
float *P2=&b;
printf(“Address of P1 = %u\n”,&P1);
printf(“value of a= %d%d%d\n”,a,*P1,*(&a));
printf(“value of b = %f%f%f\n”,b,*P2,*(&b);
}
Passing pointers to a function
#include<stdio.h>
main( ) {
char input;
scanf(“%c”,&input);
conversion(&input);
void conversion(char*c) {
*c=*c-32;
*c=*c+32; }
Relationship between array and pointer
There is a close association between pointer
and array. Array name is pointer to itself. #include<stdio.h>
void main( )
For example: {
int a[5] = {5, 6, 7, 8, 9};
int a[5],*P; int *P, i;
P = &a[0];
P=&a[0]; for(i=0; i<=4; i++)
printf("%d\n",*(P+i));
After statement p=&a[0]; p point the array }
i.e. the p contains the address of a[0] (first
address of array)
P++;
void main()
{
int a = 15;
int b = 92;
int *p;
p = larger(&a, &b);
printf("%d is larger",*p);
}
Sometimes the size of the array you declared may be insufficient. To solve this
issue, you can allocate memory manually during run-time. This is known as dynamic
memory allocation in C programming.
The malloc() function reserves a block of memory of the specified number of bytes. And, it
returns a pointer of void which can be casted into pointers of any form.
The malloc() function allocates memory and leaves the memory uninitialized, whereas the calloc()
function allocates memory and initializes all bits to zero.
Syntax of calloc()
Example:
The void pointer in C is a pointer that is not associated with any data types. It points to some data
location in the storage. This means that it points to the address of variables. It is also called the general
purpose pointer. In C, malloc() and calloc() functions return void * or generic pointers.
C free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on their own.
You must explicitly use free() to release the space.
Syntax of free()
free(ptr);
C realloc()
If the dynamically allocated memory is insufficient or more than required, you can change the size of
previously allocated memory using the realloc() function.
Syntax of realloc()
So, when we define a pointer to pointer, the first pointer is used to store the
address of the second pointer. Thus it is known as double pointers.
int main() {
int v = 76;
int *p1;
int **p2;
p1 = &v;
p2 = &p1;
printf("Value of v = %d\n", v);
printf("Value of v using single pointer = %d\n", *p1 );
printf("Value of v using double pointer = %d\n", **p2);
return 0;
}
Program to add numbers in an array using pointer
#include <stdio.h>
int add(int *s, int n)
{
int sum=0;
for(int i=0;i<n;i++)
sum+= *(s+i);
return sum;
}
int main()
{
int a[10],i,n,as=0;
printf("Enter a number:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter elements of an array [%d]",i+1);
scanf("%d",&a[i]);
}
as+=add(a,n);
printf("The total sum is %d",as);
return 0; }
WAP to find the largest in an array using pointer.
int main()
{
int *a,i,n,largest;
printf("Enter a number:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter elements of an array [%d]",i+1);
scanf("%d",(a+i));
}
largest=*(a);
for(i=0;i<n;i++)
{
if(largest<*(a+i))
{
largest=*(a+i);
}
}
printf("The total sum is %d",largest);
return 0;
}
WAP to find the length of string using pointer and function
#include <stdio.h>
void count(char *s, int n)
{
int count=0;
while(*s != '\0')
{
count++;
s++;
}
printf("The total count is %d",count);
}
int main()
{
char s[20];
int n;
printf("Enter the string:");
gets(s);
n=strlen(s);
count(s,n);
return 0; }
WAP to find the factorial and square using pointers and
functions