0% found this document useful (0 votes)
5 views16 pages

Module 4 Pointers

Uploaded by

nandankp332
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
5 views16 pages

Module 4 Pointers

Uploaded by

nandankp332
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 16

Principles of Programming using C BPOPS103

Principles of Programming using C BPOPS103

Module 4 –Part 2 (Pointers)


Strings and Pointers: Introduction, string taxonomy, operations on strings, Miscellaneous string
and character functions, arrays of strings. Pointers: Introduction to pointers, declaring pointer
variables, Types of pointers, Passing arguments to functions using pointers.

What is a pointer? Explain how the pointer variable is declared and initialized.(Dec 2018,
Jan.2015,Dec.2015,Dec.2016, June 2016,Jan 2020)

Pointer: A pointer is a variable that can hold the address of another variable.

Pointer Declaration: Pointer variables should be declared before they are used.

Syntax: datatype *pointer_name;

In above syntax data type is any valid type of data, * is dereference operator or indirection
operator. Ex: int *p;

In example, p is a pointer variable of type integer and *p can hold address of some other
variable.

Pointer initialization

It is the process of assigning an address to the pointer variable. When a pointer is declared it
points to garbage value such a pointer is called stray pointer. We must initialize pointer to
required address.
Syntax:
datatype variable_name; datatype variable_name;
datatype *pointer_name; OR datatype pointer_name=&variable_name;
pointer_name =&variable_name;

E.g.: E.g.:
int a=10; int a=10;
int *p ; //pointer declaration OR
int *p=&a;
p= &a; //Initialization of pointer variable
Here, * is dereference operator or indirection operator , & is called reference or address
operator.

CSE Dept, VCET,Puttur. Page 1


Principles of Programming using C BPOPS103

E.g. int a=10;


int *p=&a;

Here,
a=10 , p=2000 and *p=10
• The data type of pointer must be same data type of the value it is pointing to.
• The symbol ‘&’ gives address of operand. When it is associated with a variable it gives
address of that variable. In above example ‘p’ is having address of ‘a’.

Program that demonstrates the Pointers

#include<stdio.h>
void main()
{
int a=10;
int *p;
p=&a;
printf("The value of a = %d\n", a);
printf("The address of a = %u\n", &a);
printf("The value of p = %u\n", p);
printf("The value of *p = %d", *p);
}
Output
The value of a = 10
The address of a = 2161624012
The value of p = 2161624012
The value of *p = 10
***************************

[Note:
Uses of pointers:
For passing the argument by using references.
For accessing the elements of an array.
For dynamic memory allocation by using malloc() and calloc() functions .
Used in arrays, functions to improve the performance of code.
For returning multiple values.
Implementing a data structure.
For doing system-level programming.]

CSE Dept, VCET,Puttur. Page 2


Principles of Programming using C BPOPS103

POINTER EXPRESSIONS

Pointer variables can be used in expressions. For example, if p and q pointers as given below,
then following expressions are valid.

int a=10,b=20,sum,m;
int *p,*q;
p=&a;
q=&b;
sum=*p + *q;
m=sum * (*p);
*q= *p + 10;

Ex: Write a C program to add two numbers using pointers. (Jan 2020)

#include <stdio.h>
void main()
{
int n1, n2, *p, *q, sum;
printf("Enter two integers to add\n");
scanf("%d%d", &n1, &n2);
p = &n1;
q = &n2;
sum = *p + *q;
printf("Sum of entered numbers = %d\n",sum);
}

Ex: C Program that swaps two numbers using pointers.

#include <stdio.h>
void main()
{
int a=10, b=20,temp;
int *p,*q;
p=&a;
q=&b;
printf("Values before exchanging are %d and %d\n",a,b);
temp=*p;
*p=*q;
*q=temp;
printf("Values after exchanging are %d and %d\n",a,b);
}

CSE Dept, VCET,Puttur. Page 3


Principles of Programming using C BPOPS103

Ex: C program to find area of a circle

#include<stdio.h>
#define PI 3.1415927
void main()
{
float area, r;
float *pa,*pr;
pa= &area;
pr=&r;
printf("Enter value for radius\n");
scanf("%f",&r);
*pa=PI * *pr * *pr;
printf("Area=%f\n",*pa);
}
Ex: Write a program to input three numbers and then find largest of them.

#include <stdio.h>
void main ()
{
int nl, n2, n3;
int *p1=&n1, *p2=&n2, *p3=&n3;
printf(“Enter three numbers\n”);
scanf(“%d%d%d”,&num1,&num2,&num3);
if (*p1>*p2 && *p1 > *p3)
printf (" \n %d is the largest number", *p1);
else if (*p2 > *p1 && *p2 > *p3)
printf (" \n %d is the largest number", *p2);
else
printf (" \n %d is the largest number", *p3);
}
*****************************

CSE Dept, VCET,Puttur. Page 4


Principles of Programming using C BPOPS103

POINTER ARITHMETIC (Address arithmetic)

• An expression like p1++;


will cause the pointer p1 to point to the next value of its type.
• For example, if p1 is an integer pointer with an initial value, say 2800, then after the
operation p1 = p1+1, the value of p1 will be 2802, and not 2801.
• That is, when we increment a pointer, its value is increased by the 'length' of the data type
that it points to.
• Prefix or postfix increment or decrement operators can be applied on a pointer variable.
• An integer value may be added or subtracted from a pointer variable.
• When two pointers point to the same array, one pointer variable can be subtracted from
another.
• When two pointers point to the variables of the same data types, they can be compared
using relational operators.
• A pointer variable cannot be multiplied by a constant.
• Two pointer variables cannot be added.
*********************************

POINTERS AND ARRAYS

When an array is declared the name of array always point to address of the first element and
this address is called base address. Pointers can be initialized with name of array and used to
access array elements. Syntax:

datatype arrayname[size];
datatype *pointer;
pointer = arrayname;
In above syntax ‘&’ is not required while assigning array to pointers.

Ex :
int a[10];
int *p;
p=a;

In above example we have assumed the starting address a=2000 and it is base address. Array
name a points to the first element in array and pointer p is initialized with a to access array
elements.

CSE Dept, VCET,Puttur. Page 5


Principles of Programming using C BPOPS103

Ex: Write a C program to display elements of array of integers using pointer.

#include<stdio.h>

void main()

int i, n, x[100], *p;

printf("Enter value for n\n");

scanf("%d", &n);

printf("Enter integers\n");

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

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

p=x; /*Base address of array x is assigned to pointer p*/

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

printf(“%d\t", *p);

p++; /* Pointer arithmetic */

Ex: Write a C program to find sum of N integers in an array using pointer.

#include<stdio.h>
void main()
{
int i, n, sum=0, a[100], *p;
printf("Enter value for n\n");
scanf("%d", &n);
printf("Enter integers\n");
for(i=0;i<n;i++)

CSE Dept, VCET,Puttur. Page 6


Principles of Programming using C BPOPS103

{
scanf("%d",&a[i]);
}
p=a; /*Base address of array a is assigned to pointer p*/
for(i=0;i<n;i++)
{
sum=sum + *p;
p++;
}
printf("Sum=%d", sum);
}

Ex: To find the maximum of all elements stored in an array of N integers using pointers.

#include<stdio.h>
void main()
{
int i, n, large=0, a[100], *p;
printf("Enter value for n\n");
scanf("%d", &n);
printf("Enter integers\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
p=a; /*Base address of array a is assigned to pointer p*/
for(i=0;i<n;i++)
{
if(*p>large)
large=*p;
p++;
}
printf("largest is=%d", large);
}
Ex :Develop C program using pointers to compute the sum, average of all elements stored
in an array.(Jan 2021)

#include <stdio.h>
void main()
{
int i, n;

CSE Dept, VCET,Puttur. Page 7


Principles of Programming using C BPOPS103

float x[10], *p, m,sum = 0;


printf("Enter the number of terms\n");
scanf("%d", &n);
printf("Enter %d terms \n", n);
for (i = 0; i < n; i++)
{
scanf("%f", &x[i]);
}

p = x; /*Base address of array x is assigned to pointer p*/


for (i = 0; i < n; i++)
{
sum = sum + *p;
p++;

}
printf("Sum = %.2f\n", sum);
m = sum / n;
printf("Mean = %.2f\n", m);

Ex: Develop a program using pointers to compute the sum, mean and standard deviation
of all elements stored in an array of N real numbers.
(Dec.2014/Jan.2015,Dec.2015/Jan.2016,Dec.2016Jan2017,July 2021,Feb 2022)(lab pgm 14)
[ Note: Sum is

CSE Dept, VCET,Puttur. Page 8


Principles of Programming using C BPOPS103

Students, note that, above content is for your reference. ]

Develop a program using pointers to compute the sum, mean and standard deviation of all
elements stored in an array of N real numbers.
(Dec.2014/Jan.2015,Dec.2015/Jan.2016,Dec.2016Jan2017,July 2021,Feb 2022)(lab pgm 14)

#include <stdio.h>

#include <math.h>

CSE Dept, VCET,Puttur. Page 9


Principles of Programming using C BPOPS103

void main()
{
int i, n;
float x[10],*p, m, sd, sum=0, sum1=0;
printf("Enter the number of terms\n");
scanf("%d", &n);

printf("Enter terms \n");


for (i = 0; i < n; i++)
{
scanf("%f", &x[i]);
}
p=x; /*Base address of array x is assigned to pointer p */

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

sum = sum + *p;

p++; /* Address arithmetic */

printf("Sum = %f\n", sum);

m = sum / n;

printf("Mean = %.2f\n", m);

p=x; /* Base address array x is re-assigned to pointer p */

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

sum1 = sum1 + pow((*p - m), 2);

p++; /* Address arithmetic */

sd = sqrt(sum1/n);

printf("Standard Deviation = %.2f\n", sd);

CSE Dept, VCET,Puttur. Page 10


Principles of Programming using C BPOPS103

PASSING ARGUMENTS TO FUNCTIONS USING POINTERS

To use pointers for passing arguments to a function, the programmer must do the following

• Declare the function parameters as pointers and Use the pointers in the function body.
void sum (int *a, int *b, int *t)
Ex:
{
*t =*a + *b;
}
• Pass the addresses as the actual argument when the function is called.

Ex : void main()
{ …….
sum (&num1, &num2, &total);
}

Ex : Write a program to add two integers by passing arguments to function using pointers.

#include <stdio.h>
void sum (int *a, int *b, int *t); /* function declaration */
int main ()
{
int num1, num2, total;
printf (" \n Enter two numbers: ") ;
scanf ("%d%d", &num1,&num2);
sum (&num1, &num2, &total); /* function call */
printf ("\n Total = %d", total);
return 0;
}
void sum (int *a, int *b, int *t) /* function definition */
{
*t =*a + *b;
}
Output:
Enter two numbers: 23 45
Total = 68

CSE Dept, VCET,Puttur. Page 11


Principles of Programming using C BPOPS103

Ex: Write C program to find the biggest of three integers by passing arguments to function
using pointers.

#include <stdio.h>
void greater (int *a, int *b, int *c, int *lg) ;
void main ()
{
int num1, num2, num3, large;
printf (" \n Enter three numbers: ") ;
scanf ("%d%d%d", &num1,&num2,&num3);
greater( &num1, &num2, &num3, &large);
printf("largest is=%d", large);
}
void greater (int *a, int *b, int *c, int *lg)
{
if (*a > *b && *a > *c)
*lg = *a;
else if (*b > *a && *b > *c)
*lg = *b;
else
*lg =*c;
}
Output
Enter three numbers: 56 444 3
largest is=444

Same Program using ternary operator

#include <stdio.h>
void greater (int *a, int *b, int *c, int *lg) ;

CSE Dept, VCET,Puttur. Page 12


Principles of Programming using C BPOPS103

int main ()
{
int num1, num2, num3, large;

printf (" \n Enter three numbers: ") ;

scanf ("%d%d%d", &num1,&num2,&num3);

greater( &num1, &num2, &num3, &large);

printf("largest is=%d", large);

void greater (int *a, int *b, int *c, int *lg)

{
*lg = *a > *b? ( *a > *c ? *a : *c) : ( *b > *c ? *b : *c);
}

Ex: Write C program to calculate the area of a triangle.

#include <stdio .h>


void calculate_area (float *b, float *h, float *a);
void main ()

{
float base, height, area;
printf (" Enter the base of the triangle: ");
scanf ("%f", &b);
printf (" Enter the height of the triangle: ");
scanf ("%f",&h);
calculate_area (&base, &height, &area) ;
printf(" Area of the triangle is %f", area);

void calculate _area (float *b, float *h, float *a)


{

*a = 0.5 * (*b) * (*h) ;

Output
Enter the base of the triangle: 10

CSE Dept, VCET,Puttur. Page 13


Principles of Programming using C BPOPS103

Enter the height of the triangle: 5


Area of the triangle is 25.00

***********************************

TYPES OF POINTERS

NULL POINTERS

• NULL pointer which is a special pointer value that does not point anywhere.

• NULL pointer does not point to any valid memory address.

• To declare a null pointer we use the predefined constant NULL, which is defined in
several standard header files including <stdio.h>, <stdlib. h> and <string.h>.

• After including any of these files write,


int *ptr = NULL;

• We can check whether a given pointer variable stores address of some variable or
contains a NULL by writing,
if (ptr == NULL)
Statement block;

• Null pointers are used in situations where one of the pointers in the program points to
different locations at different times. In such situations it is always better to set it to a null
pointer when it does not point anywhere and to test to see if it's a null pointer before
using it.

GENERIC POINTERS

• A generic pointer is a pointer variable that has void as its data type.
• The void pointer, or the generic pointer, is a special type of pointer that can be used to
point to variables of any data type.
• It is declared using the void keyword
o void *ptr ;
• We need to type cast a void pointer (generic pointer) to another kind of pointer before
using it.
• Generic pointers are often used when we want pointer to point to data of different types at
different time.
Ex :

CSE Dept, VCET,Puttur. Page 14


Principles of Programming using C BPOPS103

#include <stdio.h>
void main ( )
{

int x=10;
char ch = 'A';
void *gp;
gp = &x;
printf (" Generic pointer points to the integer value = %d", * (int*) gp) ;
gp = &ch;
printf (" Generic pointer now points to the character %c", * (char*) gp);
}
Output
Generic pointer points to the integer value = 10
Generic pointer now points to the character = A

******************************************

VTU Question paper questions

1. Define pointers. Explain pass by value and pass by reference and an example. (June
2019)
2. What is a pointer? Explain how the pointer variable is declared and initialized.(Dec 2018,
Jan.2015,Dec.2015,Dec.2016, June 2016,Jan 2020)
3. Develop a program using pointers to compute the sum, mean and standard deviation of
all elements stored in an array of N real numbers.
(Dec.2014/Jan.2015,Dec.2015/Jan.2016,Dec.2016Jan2017,July 2021,Feb 2022)(lab pgm
14)
4. Write a C program to add two numbers using pointers(Jan 2020)
5. Develop C program using pointers to compute the sum, average of all elements stored in
an array.(Jan 2021)
******************************
Pointers and Character Strings
Syntax for declaration:
char stringname[size];
char *pointer;
pointer = stringname;

E.g.: char str[100];


char *p;

CSE Dept, VCET,Puttur. Page 15


Principles of Programming using C BPOPS103

p=str;
String is an array of character in which declaration and initialization are like arrays. Array data
type here is character.
Q) Write a program to find string length using pointers
#include<stdio.h>
void main()
{
char str[100]="Raj";
char *ptr = str;
int length;
printf("string is %s\n",str);
while(*ptr!='\0')
{
ptr++;
}
length=ptr-str;
printf("Length is %d\n",length);
}
Output: string is Raj
Length is 3
Q) Write a program to copy one string to another using pointers. (Appeared in June 2018)
#include<stdio.h>
void main()
{
char str1[100],str2[100], *p1, *p2;
p1 = str1;
p2 = str2;
printf("Enter string\n");
scanf("%s",str1);
while(*p1!='\0')
{
*p2=*p1;
p1++;
p2++;
}
*p2='\0';
printf("Copied string is %s\n",str2);
}
Output: Enter string
Raj
Copied string is Raj

CSE Dept, VCET,Puttur. Page 16

You might also like