Saturday, October 16, 2021

Assignment 1. Simple Pointers

 Assignment 1. Simple Pointers

 Pointers:- 

Pointers in C language is a variable that stores/points the address of another variable. 

A Pointer in C is used to allocate memory dynamically i.e. at run time.

The pointer variable might be belonging to any of the data type such as int, float, char, double, short etc.

·         Pointer Syntax : data_type *var_name; 

·         Example : int *p;  char *p;

Where, * is used to denote that “p” is pointer variable and not a normal variable.

 

 

KEY POINTS TO REMEMBER ABOUT POINTERS IN C:

·         Normal variable stores the value whereas pointer variable stores the address of the variable.

·         The content of the C pointer always be a whole number i.e. address.

·         Always C pointer is initialized to null, i.e. int *p = null.

·         The value of null pointer is 0.

·         & symbol is used to get the address of the variable.

·         * symbol is used to get the value of the variable that the pointer is pointing to.

·         If a pointer in C is assigned to NULL, it means it is pointing to nothing.

·         Two pointers can be subtracted to know how many elements are available between these two pointers.

·         But, Pointer addition, multiplication, division are not allowed.

·         The size of any pointer is 2 byte (for 16 bit compiler).

EXAMPLE PROGRAM FOR POINTERS IN C:

#include<stdio.h>  
int main(){  
int number=50;    
int *p;      
p=&number;//stores the address of number variable    
printf("Address of p variable is %x \n",p); // p contains the address of the number therefore printing p gives the address of number.     
printf("Value of p variable is %d \n",*p); // As we know that * is used to dereference a pointer therefore if we print *p, we will get the value stored at the address contained by p.    
return 0;  
}    

 OUTPUT:-

Address of number variable is fff4

Address of p variable is fff4

Value of p variable is 50


Pointer to array:-

int arr[10]; 

int *p[10]=&arr; // Variable p of type pointer is

pointing to the address of an integer array arr. 

 

Pointer to a function:-

void show (int); 

void(*p)(int) = &display; // Pointer p is pointing to

the address of a function 

 

Pointer to structure:-

struct st { 

    int i; 

    float f; 

}ref; 

struct st *p = &ref;

 


  Advantage of pointer:- 

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees, etc. and used with arrays, structures, and functions.

2) We can return multiple values from a function using the pointer.

3) It makes you able to access any memory location in the computer's memory.


Types of Pointers in C

Null Pointer:

We can create a null pointer by assigning null value during the pointer declaration. This method is useful when you do not have any address assigned to the pointer. A null pointer always contains value 0.

 void Pointer:

The void pointer within C is a pointer that is not allied with any data types. This points to some data location within the storage means points to that address of variables. It is also known as a general-purpose pointer. In C, malloc() and calloc() functions return void * or generic pointers.

Example:

int x= 10;

char y= ‘a’;

void *p= &x //void pointer contains address of int x

p = &y //void pointer holds of char y

 

Wild Pointer:

Pointers that are not initialized are called wild pointers. This pointer may be initialized to a non-NULL garbage value which may not be a valid address. 

Example:

int main()

{

int *p; // wild pointer

*p= 10;

}

Remember if a pointer p points to any known variable, then it is not a wild pointer. In the below program p is a wild pointer until it points to x.

int main()

{

int = *p; // wild pointer

int x= 20;

p= &x // p is not a wild pointer now

}

 

Dangling Pointer:

    Dangling pointers arise during object destruction, when an object that has an incoming reference is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory.

 

Example 1:

Deallocation of memory:

#include<stdio.h>

#include<stdlib.h>

int main()

{

   int *ptr = (int *)malloc(sizeof(int));

   free(ptr);

   ptr = NULL;

}

Complex Pointer:

   Before knowing how to read complex pointers then

        you should first know associativity and precedence.

Associativity: Order operators of equal precedence within an expression are employed.

Precedence: Operator precedence describes the order in which C reads expressions.

Operator

Precedence

Associative

(),[]

1

Left to Right

*,Identifier

2

Right to Left

Data Type

3

·         (): this operator is used to declare and define the function.

·         []: this is an array subscript operator.

·         *: this is a pointer operator.

·         Identifier: this is the name of a pointer.

·         Data type: this is the type of variable.  

Example:

int (*p)(int (*)[3], int (*)void)) 

 

Near Pointer:

·         Near pointer means a pointer that is utilized to bit address of up to 16 bits within a given section of that computer memory which is 16 bit enabled.

·         It can only access data of the small size of about 64 kb within a given period, which is the main disadvantage of this type of pointer.

Example:

#include<stdio.h>

int main()

{

   int a= 300;

   int near* ptr;

   ptr= &a;

   printf(“%d”,sizeof ptr);

   return 0;

}

Output: 3

Far Pointer:

·         A far pointer is typically 32 bit which can access memory outside that current segment. 

·         To utilize the far pointer, the compiler allows a segment register to save segment address, then another register to save offset inside the current segment.

Example: 

#include<stdio.h>

int main()

{

  int a= 10;

  int far *ptr;

  ptr=&a;

  print(“%d”, sizeof ptr);

  return 0;

}

Huge Pointer:

·         Same as far pointer huge pointer is also typically 32 bit which can access outside the segment.

·         A far pointer that is fixed and hence that part of that sector within which they are located cannot be changed in any way; huge pointers can be.

Example:

#include<stdio.h>

int main()

{

   char huge *far *a;

   printf(“%d%d%d”, sizeof(a), size(*a), sizeof(**a));

   return 0;

}

Output: 4 4 1.

Struct pointer:

·         Pointers can be utilized to refer to a struct by its address. This helps pass structs to a function.

·         The pointer can be dereferenced by the * operator.

·         The -> operator dereferences the pointer to the left operand and later accesses the value of a member of the right operand.

 


Pointer Arithmetic in C :-

        We can perform arithmetic operations on the pointers like addition, subtraction, etc. However, as we know that pointer contains the address, the result of an arithmetic operation performed on the pointer will also be a pointer if the other operand is of type integer. In pointer-from-pointer subtraction, the result will be an integer value. Following arithmetic operations are possible on the pointer in C language:

o    Increment

o    Decrement

o    Addition

o    Subtraction

o    Comparison

Incrementing Pointer in C

If we increment a pointer by 1, the pointer will start pointing to the immediate next location. This is somewhat different from the general arithmetic since the value of the pointer will get increased by the size of the data type to which the pointer is pointing.

 

The Rule to increment the pointer is given below:

new_address= current_address + i * size_of(data type)  

 

Let's see the example of incrementing pointer variable on 64-bit architecture

#include<stdio.h>  
int main(){  
int number=50;        
int *p;//pointer to int      
p=&number;//stores the address of number variable        
printf("Address of p variable is %u \n",p);        
p=p+1;        
printf("After increment: Address of p variable is %u \n",p); // in our case, p will get incremented by 4 bytes.      
return 0;  
}    

 Decrementing Pointer in C

new_address= current_address - i * size_of(data type)  

 Pointer addition in C

We can add a value to the pointer variable. The formula of adding value to pointer is given below:

 new_address= current_address + (number * size_of(data type))  

 Pointer Subtraction in C

Like pointer addition, we can subtract a value from the pointer variable. Subtracting any number from a pointer will give an address. The formula of subtracting value from the pointer variable is given below:

new_address= current_address - (number * size_of(data type))  

 Illegal Arithmatic with pointers:-

There are various operations which can not be performed on pointers. Since, pointer stores address hence we must ignore the operations which may lead to an illegal address, for example, addition, and multiplication. A list of such operations is given below.

o    Address + Address = illegal

o    Address * Address = illegal

o    Address % Address = illegal

o    Address / Address = illegal

o    Address & Address = illegal

o    Address ^ Address = illegal

o    Address | Address = illegal

o    ~Address = illegal

 


example to make a pointer pointing to the function.

#include<stdio.h>  
int addition ();  
int main ()  
{  
    int result;   
    int (*ptr)();  
    ptr = &addition;  
    result = (*ptr)();  
    printf("The sum is %d",result);  
}  
int addition()  
{  
    int a, b;   
    printf("Enter two numbers?");  
    scanf("%d %d",&a,&b);  
    return a+b;  

 

OUTPUT:-

Enter two numbers?10 15

The sum is 25 


The pointer to an array of functions is a pointer pointing to an array which contains the pointers to the functions. Consider the following example.

#include<stdio.h>  
int show();  
int showadd(int);  
int (*arr[3])();  
int (*(*ptr)[3])();  
  
int main ()  
{  
    int result1;  
    arr[0] = show;  
    arr[1] = showadd;  
    ptr = &arr;  
    result1 = (**ptr)();  
    printf("printing the value returned by show : %d",result1);  
    (*(*ptr+1))(result1);  
}  
int show()  
{  
    int a = 65;  
    return a++;  
}  
int showadd(int b)  
{  
    printf("\nAdding 90 to the value returned by show: %d",b+90);  
}  

 

OUTPUT:-

printing the value returned by show : 65

Adding 90 to the value returned by show: 155

 

Assignment :


Set A . Write C programs for the following problems.

1. Write a function which takes hours, minutes and seconds as parameters and an integer s and increments the time by s seconds. Accept time and seconds in main and Display the new time in main using the above function.

/*C Program to find maximum and minimum element in array using pointer */

#include <stdio.h>

#include <stdlib.h>

void max_min(int num[],int length,int *max,int *min);

int main()

{

 int len;

 int num[len];

 int i,max,min;

 printf("How many numbers do you wanna input ?");

 scanf("%d",&len);

 printf("Enter %d numbers to find the biggest and small (enter x to terminate)",len);

 for(i=0;i<len-1;i++)

 {

 scanf("%d",&num[i]);

 }

max_min(num,len,&max,&min);

printf("Biggest number :%d",max);

 printf("Smallest number :%d",min);

system("pause");

 return 0;

}

void max_min(int num[],int length,int *max,int *min)

{

 int k;

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

 {

 if(num[k]>*max)

 *max=num[k];

 else if(num[k]<*min)

 *min=num[k];

 }

} 

 

2. Write a program to display the elements of an array containing n integers in the reverse order using a pointer to the array.

 

#include <stdio.h>

void main()

{

int n, i, arr1[15];

int *pt;

printf(" Input the number of elements to store in the array (max 15) : ");

scanf("%d",&n);

pt = &arr1[0]; // pt stores the address of base array arr1

printf(" Input %d number of elements in the array : \n",n);

for(i=0;i<n;i++)

 {

 printf(" element - %d : ",i+1);

 scanf("%d",pt);//accept the address of the value

 pt++;

}

pt = &arr1[n - 1];

printf("\n The elements of array in reverse order are :");

for (i = n; i > 0; i--)

{

 printf("\n element - %d : %d ", i, *pt);

 pt--;

}

}

 

 

Set B . Write C programs for the following problems.

1. Accept n integers in array A. Pass this array and two counter variables to a function which will set the first counter to the total number of even values in the array and the other to the total number of odd values. Display these counts in main. (Hint: Pass the addresses of the counters to the function)

 

// Solution to the problem statement using C pointers.

 

#include<stdio.h>

#include<stdlib.h>

int countEven(int n, int *a)

{

int Even=0;

for(int i=0;i<n;i++)

{

if(*(a+i)%2==0)

{

Even++;

}

}

return Even;

}

int countOdd(int n,int*a)

{

int Odd=0;

for(int i=0;i<n;i++)

{

if(*(a+i)%2!=0)

{

Odd++;

}

}return Odd;

}

int main()

{

int *a,n,Even=0,Odd=0;

scanf(“%d”,&n);

a=(int*)malloc(n*sizeof(int));

for(int i=0;i<n;i++)

{

scanf(“%d”,(a+i));

}

printf(“Odd:%d\n”,countOdd(n,a));

printf(“Even:%d”,countEven(n,a));

 

return 0;

}

 

2. Write a function which accepts a number and three flags as parameters. If the number is even, set the first flag to 1. If the number is prime, set the second flag to 1. If the number is divisible by 3 or 7, set the third flag to 1. In main, accept an integer and use this function to check if it is even, prime and divisible by 3 or 7. (Hint : pass the addresses of flags to the function)

  

 Write a program to read two integers using pointers and perform all arithmetic operations on them.

 /* C Program to Perform All Arithmetic Operations using Pointers:*/

#include<stdio.h>

int main()

{

int no1,no2;

int *ptr1,*ptr2;

        int sum,sub,mult;

        float div;   


    printf("Enter number1:\n");

    scanf("%d",&no1);

    printf("Enter number2:\n");

    scanf("%d",&no2);

    ptr1=&no1;//ptr1 stores address of no1

    ptr2=&no2;//ptr2 stores address of no2

    sum=(*ptr1) + (*ptr2);

    sub=(*ptr1) - (*ptr2);

    mult=(*ptr1) * (*ptr2);

    div=(*ptr1) / (*ptr2);

      printf("sum= %d\n",sum);

    printf("subtraction= %d\n",sub);

    printf("Multiplication= %d\n",mult);

    printf("Division= %f\n",div);

    return 0;

}


Write a program to accept an integer using pointer and check whether it is even or odd.

/*2. Write a program to accept an integer using pointer and check whether it is even or odd.*/

#include<stdio.h>

int main()

{

  int  n, rem;

  int *pn;

  printf("Enter any number:");

  scanf("%d ",&n);

  pn=&n;

   rem=(*pn)%2;

  if(rem==0)

  printf("%d is even", *pn);

    else

      printf("%d is odd", *pn);

    return 0;

}


Write a program to find maximum from two integers using pointers.

/*3. Write a program to find maximum from two integers using pointers.**/

#include<stdio.h>

int main()

{

  float x, y;

  float *px, *py;

  px=&x, py=&y;

  printf("Enter Two number:");

  scanf("%f %f", px, py);

  if(*px > *py)

  printf("Biggest = %.2f", *px);

    else

      printf("Biggest = %.2f", *py);

    return 0;

}

 

Write a program to display the elements of an array containing n integers in the reverse order using a pointer to the array.

/*4. Write a program to display the elements of an array containing n integers in the reverse order using a pointer to the array.*/

#include <stdio.h>

void main() 

{

   int n, i, arr1[15];

   int *pt;

 printf(" Input the number of elements to store in the array (max 15) : ");

   scanf("%d",&n);

   pt = &arr1[0];  // pt stores the address of base array arr1 

   printf(" Input %d number of elements in the array : \n",n);

   for(i=0;i<n;i++)

      {

  printf(" element - %d : ",i+1);

  scanf("%d",pt);//accept the address of the value

  pt++;

      }

 pt = &arr1[n - 1];

   printf("\n The elements of array in reverse order are :");

   for (i = n; i > 0; i--) 

   {

      printf("\n element - %d : %d  ", i, *pt);

      pt--;

   }

}


1. Write a program to read N integers in an array using pointers and display minimum from them.

#include<stdio.h>  

   

int main()  

{  

    int a[20], i, N,*small;  

  

   printf("\n Enter no of elements :");

   scanf("%d",&N);

    printf("Enter %d integer numbers\n", N);  

    for(i = 0; i < N; i++)  

        scanf("%d", &a[i]);  

      small = &a[0];  

      for(i = 1; i < N; i++)  

    {  

        if( *(a + i) < *small)  

            *small = *(a + i);  

    }  

      printf("Smallest Element In The Array: %d\n", *small);  

      return 0;  

}   


2. Write a function that takes radius of as parameter and two variables. Set first variable to area of circle and second to perimeter of circle. Accept radius in main and also display area and perimeter in main using the above function.(Hint: Pass the addresses of the variables to the function to get area and perimeter)

#include<stdio.h>

void area(int *r,float *a)

{

*a=(22*(*r)*(*r))/7;

}

void perimeter(int *r,float *p)

{

*p=2*3.142*(*r);

}

int main()

{

int r;

float a=1,p=1;

printf("enter radius of the circle: ");

scanf("%d",&r);

        area(&r,&a); 

        parimeter(&r,&p);

printf("Area Of Circle: %f\n",a);

       printf("Perimeter of Circle: %f\n",p);

return 0;

}


4. Accept n integers in array A in main. Write a function which takes this array as parameter and find minimum and maximum from it. Display these values in main.

/*C Program to find maximum and minimum element in array using pointer */

#include <stdio.h>

#include <stdlib.h>

 void max_min(int num[],int length,int *max,int *min);

 int main()

{

    int len;

    int num[len];

    int i,max,min;

    printf("How many numbers do you wanna input ?");

    scanf("%d",&len);

    printf("Enter %d numbers to find the biggest and small (enter x to terminate)",len);

    for(i=0;i<len-1;i++)

    {

        scanf("%d",&num[i]);

    }

     max_min(num,len,&max,&min);

     printf("Biggest number :%d",max);

    printf("Smallest number :%d",min);

     system("pause");

    return 0;

void max_min(int num[],int length,int *max,int *min)

{

    int k;

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

    {

        if(num[k]>*max)

            *max=num[k];

            else if(num[k]<*min)

                *min=num[k];

    }

}


No comments:

Post a Comment