Pointers

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 30

ASSIGNMENT-3

POINTERS
1.Define pointers and declaration syntax of pointers with examples.
Ans: A pointer is a variable that represents the memory location of a data item, such as a
variable or an array element.Pointers contain the address of some other
variables.Additearation with a * before the variable name creates a pointer.
The declaration syntax of pointers isdatatype *pointer name
eg- int *ptr;
char *ch;

2. Explain the difference between null pointer and void pointer.


Ans: The differences between null pointer and void pointer area) A null pointer can take any pointer type,but do not point to any valid reference or memory
address whereas a void pointer is a special type of pointer of void and denotes that it can
point to any data type.
b) Null pointers returns null value whereas void pointer returns no value.
c) Null pointer is a value, while void pointer is a type.

3. What is an array of pointers? How is it different from pointer to an array?


Ans: An array of pointers is similar to an array of any predefined data types.As a pointer
variable always contains an address, an array of pointers is a collection of addresses.These
can be addresses of ordinary isolated variables or of array elements.

On the other hand, pointer to an array means the base address of the array.For example
void main()
{
char* test[]={"Name",Address","Ph No"};
return;
}
Here test is an array and every element of this array points to particular string.

4. Explain the advantages and disadvantages of pointers.


Ans: The advantages of pointers area) It provide direct access to memory.
b) It provide a way to return more than one value to the function.
c) It reduces the storage space and complexity of the program and also it reduces the
execution time of the program.
d) It provides an alternative way to access array elements.
e) Pointers can be used to pass information back and forth between the calling function and
the called function.
f) Pointers allows us to perform dynamic memory allocation and deallocation.
g) Addresses of objects can be extracted using pointers.

The disadvantages of pointers area) Uninitialized pointers might cause segmentation fault.

b) Dynamically allocated block needs to be freed explicitly while using pointers.Otherwise, it


would lead to memory leakage.
c) Pointers are slower than normal variables.
d) If we use a pointer to read a memory location but that pointer is pointing to an incorrect
location then we may read incorrect values.

5. Explain the term dynamic memory allocation. Also differentiate between malloc(),
calloc() and realloc() with a program as an example.
Ans: The process of allocating memory to the variables during execution of the program is
called dynamic memory allocation.
eg- int arr[100]
When above statement is executed consecutive space for 100 integers is allocated, out of
which we may be using only 10% and the rest of the space gets wasted.To overcome this
and utilise memory efficiently we dynamically allocate memory so that only the amount of
memory that is required is reserved.
Some dynamic memory allocation functions are malloc(), calloc() and realloc().
a) malloc()
The name malloc stands for "memory allocation". The function malloc() reserves a block of
memory of specified size and return a pointer of type void which can be casted into pointer
of any form.
Syntax of malloc()
ptr=(cast-type*)malloc(byte-size)
eg- ptr=(int*)malloc(100*sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes
respectively and the pointer points to the address of first byte of memory.

b) calloc()
The name calloc stands for "contiguous allocation". The only difference between malloc()
and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates
multiple blocks of memory each of same size and sets all bytes to zero.
Syntax of calloc()
ptr=(cast-type*)calloc(n,element-size);
eg.- ptr=(float*)calloc(25,sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each of
size of float, i.e, 4 bytes.
c) realloc()
realloc() adjusts the amount of memory allocated to the block to size, copying the contents
to a new location if necessary.

Syntax of realloc()
ptr=(cast-type*)realloc(cast-type*ptr;size of (data type));
A program to differentiate between malloc(), calloc() and realloc() is#include<stdio.h>
#include<string.h>
#include <stdlib.h>
int main()
{
char *mem_allocation;
mem_allocation=malloc(20*sizeof(char));
if(mem_allocation==NULL)

{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_allocation,"How are you?");
}
printf("Dynamically allocated memory content: %s\n",mem_allocation);
mem_allocation=realloc(mem_allocation,100*sizeof(char));
if(mem_allocation==NULL)
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy(mem_allocation,"Space is extended upto 100 characters");
}
printf("Resized memory: %s\n",mem_allocation);
free(mem_allocation);
}
6. Differentiate between pointers to constant and constant to pointers.
Ans: pointer to constant: These type of pointers are the one which cannot change the value
they are pointing to.This means that they cannot change the

value of variable whose address they are holding.A pointer to a constant is declared as :
const int*ptr
constant to pointer: These type of pointers are the one which cannot change address they
are pointing to.This means that suppose there is a pointer which points to a variable (or
stores the address of the variable).Now if we try to point the pointer to some other variable
(or try to make the pointer store address of some other variables), then constant pointers
are incapable of this.A constant pointer is declared as:
int * const ptr

7. Differentiate between ptr++ and *ptr++?


Ans: ptr++ will make the pointer point to the next address in the memory.On the other hand,
*ptr++ increments the content of address ptr is pointing to.

8) How can you have array of function pointers? Illustrate with examples.
Ans:
Let us consider this example:
#include<stdio.h>

int display();
int(*arr[3])();
int(*(*ptr)[3])();

int main() {
arr[0]=display;
arr[1]=getch;
ptr=&arr;

printf("%d",(**ptr)());

(*(*ptr+1))();
return 0;
}

int display(){
int num = 25;
return num;
}
Explanation:
Step 1 : Array of Function
int(*arr[3])();
above statement tell that
arr is an array of size 3.
Array stores address of functions
Array stores address of function having integer as return type and does not takes
any parameter.

Step 2 : Declaring Array of function Pointer


int(*(*ptr)[3])();
It is array of function pointer which points to array of function.
Step 3 : Store function names inside function array
arr[0] = display;
arr[1] = getch;
Step 4 : Store address of function Array to Function Pointer
ptr = &arr;
Step 5 : Calling Function
following syntax is used to call display function
(**ptr)();
this syntax is used to call getch function
(*(*ptr+1))();

9) What is memory leakage problem. Explain with example.


Ans: A memory leak is the gradual loss of available computer memory when a program (an
application or part of the operating system) repeatedly fails to return memory that it has
obtained for temporary use.It occurs when memory is allocated but not released when it is
no longer required.This causes unnecessary consumption of memory and results into slow
execution of program. Memory leak can eventually cause the program or the system to
terminate.
An example of memory leak is#include<stdlib.h>
void f()

{
int *ptr = (int *) malloc(sizeof(int));
return;
}

10) What is dangling pointer. Explain with an example.


Ans: Dangling pointers arise when an object is deleted or de-allocated, without modifying
the value of the pointer, so that the pointer still points to the memory location of the deallocated memory.In short pointer pointing to non-existing memory location is called
dangling pointer.
For solving the problem of dangling pointer we will use dynamic memory allocation
function.
eg-

#include<stdio.h>
main()
{
int *p
p=increment(1);
printf(%d;*p);
}
int *increment(intn)

{
int *ptr;
ptr=(int*)malloc(size of (int));
*ptr=n+1;

return ptr;
}

11) Differentiate between *(arr+i) and (arr+i).


Ans: *(arr+i) gives the content of the (i+1)th element of the array, i.e*(arr+i)=arr[i].
On the other hand, (arr+i) is a pointer to arr[i], i.earr+i=arr+i*size of (int)
12.Find Output:
main()
{
int x=3;
int *a=&x,*b=a;
int **c=&b;
printf(%d%d%d,*a,*b,**c);
}
Ans:
Output: 3 3 3
13.What is the output of the following program?
main()
{
int a[4]={57,32,79,87};
int *x=a;

printf(%d %d %d, *x,*x+2,*(x+2));


}

Ans:
Output will be: 57 59 79
14.Write a program to print altenate letters of a string.
Ans:
#include<stdio.h>
#include<stdlib.h>
int main()
{
char name[30],i,*p[30],j;
printf("\nEnter a string");
gets(name);
for(i=0,j=0;name[i]!='\0';i=i+2,j++)
{
p[j]=&name[i];
printf("%c",*p[j]);
}
return 0;
}
Output Screen:

15. Write a program to obtain the number of elements from the user, store it
dynamically in memory and find out the smallest element in the list.
Ans:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,n,*p,t;
printf("\nHow many numbers do you want to enter?");
scanf("%d",&n);
p=(int*)malloc(n*sizeof(int));
printf("\nEnter numbers");
for(i=0;i<n;i++)

{
scanf("%d",p+i);
}
for(i=1;i<n;i++)
{
if(*p>*(p+i))
{
*p=*(p+i);
}
}
printf("\nSmallest number of the numbers entered=%d",*p);
return 0;
}
Output Screen:

16.Write a program to store addresses of array elements in another array.


Ans:
#include<stdio.h>
int main()
{
int a[10],*p,n,i;
printf("\nEnter range of the array");
scanf("%d",&n);
printf("\nEnter elements in array");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
p=&a[i];
printf("\n Address of %d position element of the array=%d",i,p);
}
return 0;
}
Output Screen:

17.Write a program to demonstrate working of calloc().


Ans:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,n,*p;
printf("\nHow many numbers do you want to enter?");
scanf("%d",&n);
p=(int*)calloc(n,sizeof(int));
printf("\nEnter numbers");
for(i=0;i<n;i++)3
{

scanf("%d",p+i);
}
for(i=1;i<n;i++)
{
if(*p<*(p+i))
{
*p=*(p+i);
}
}
printf("\nLargest number of the numbers entered=%d",*p);
return 0;
}
Output Screen:

18.Write a program to reverse a string using pointers.


Ans:
#include<stdio.h>
int string_length(char*);
void reverse(char*);
int main()
{
char string[100];

printf("Enter a string\n");
gets(string);

reverse(string);

printf("Reverse of entered string is \"%s\".\n", string);

return 0;
}

void reverse(char *string)


{
int length, c;
char *begin, *end, temp;

length = string_length(string);
begin = string;
end = string;

for (c = 0; c < length - 1; c++)


end++;

for (c = 0; c < length/2; c++)


{
temp = *end;
*end = *begin;
*begin = temp;

begin++;
end--;
}
}

int string_length(char *pointer)


{
int c = 0;

while( *(pointer + c) != '\0' )


c++;

return c;
}
Output Screen:

19. Write a program to implement call by reference using functions to swap two
integer numbers.
Ans:
#include<stdio.h>
int swap(int*,int*);
int main()
{

int a,b;
printf("\nEnter the first number");
scanf("%d",&a);
printf("\nEnter the second number");
scanf("%d",&b);
printf("\nNumbers berfore swapping are: %d and %d",a,b);
swap(&a,&b);
printf("\nNumbers after swapping are: %d and %d",a,b);
return 0;
}
int swap(int *p,int *q)
{
int r;
r=*p;
*p=*q;
*q=r;
return (*p,*q);

}
Output Screen:

20. Write a program to copy a string using pointers and not using strcpy functions.
Ans:
#include<stdio.h>
int main()
{
char a[50],*p[50],i,n=0;
printf("\nEnter a string");
gets(a);
for(i=0;a[i]!='\0';i++)
{
p[i]=&a[i];
}
printf("\nThe copied string is: ");

for(i=0;a[i]!='\0';i++)
{
printf("%c",*p[i]);
}
return 0;
}
Output Screen:

21. Write a program for addition of a matrix using pointers.


Ans:
#include<stdio.h>
int main()
{
int p[10],q[10],i,n,sum;
int *a,*b;

printf("\nEnter range");
scanf("%d",&n);
printf("\nEnter elements in 1st array:");
for(i=0;i<n;i++)
{
scanf("%d",&p[i]);
}
printf("\nEnter elements in 2nd array:");
for(i=0;i<n;i++)
{
scanf("%d",&q[i]);
}
a=p;b=q;
printf("\nSum of the elements of the array\n");
for(i=0;i<n;i++)
{
sum=*(a+i)+*(b+i);
printf("%d\n",sum);
}
return 0;
}
Output Screen:

22. Write a program to read and print a floating point array. The space for the array
should be allocated at the run time.
Ans:
#include<stdio.h>
int main()
{
int n,p,i;
printf("\nEnter the size of the array");
scanf("%d",&n);
float arr[n];
printf("\nEnter range of array");
scanf("%d",&p);
printf("Enter the elements in the array");

for(i=0;i<p;i++)
{
scanf("%f",&arr[i]);
}
printf("\nThe elements entered in the array are:");
for(i=0;i<p;i++)
{
printf("\n %.3f",arr[i]);
}
return 0;
}
Output Screen:

23.Write a program to print HELLO WORLD using pointers.

Ans:
#include<stdio.h>
#include<stdlib.h>
int main()
{
char name[30]="HELLO WORLD",*p[30];
int i,j;
for(i=0,j=0;name[i]!='\0';i++,j++)
{
p[j]=&name[i];
printf("%c",*p[j]);
}
return 0;
}

24. Write a program to subtract two integer values using pointers.


Ans:
#include<stdio.h>
int sub(int*,int*);
int main()
{
int a,b,c;
printf("\nEnter the first number");
scanf("%d",&a);
printf("\nEnter the second number");
scanf("%d",&b);
c=sub(&a,&b);
printf("\nSubtaction of %d from %d i.e %d-%d=%d",b,a,a,b,c);
return 0;
}
int sub(int *p,int *q)
{
int r;
r=*p-*q;
return (r);
}
Output Screen:

25. Write a program to find smallest of three integers values using pointer.
Ans:
#include<stdio.h>
main()
{
int a,b,c,*p,*q,*r,small;
printf("\nEnter three numbers");
scanf("%d%d%d",&a,&b,&c);
p=&a;
q=&b;
r=&c;
small=(*p<*q&&*p<*r)?*p:(*q<*r)?*q:*r;
printf("\nSmallest of the three entered numbers= %d",small);

}
Output Screen:

Submitted By:
Partha Aich
Mechanical Department
14-12-078

You might also like