0% found this document useful (0 votes)
106 views24 pages

Ch-3 Pointers

The document discusses pointers in C programming. It defines pointers as special variables that store memory addresses rather than values. Pointers provide several advantages including direct memory access, returning multiple values from functions, reducing storage space and complexity, and allowing dynamic memory allocation. The document outlines various uses of pointers, their characteristics, types including null, void, and wild pointers, and arithmetic operations that can be performed on pointers like addition, subtraction, incrementing and decrementing. It also discusses pointers to arrays and how pointers allow implementing data structures.

Uploaded by

Vekariya Kartik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
106 views24 pages

Ch-3 Pointers

The document discusses pointers in C programming. It defines pointers as special variables that store memory addresses rather than values. Pointers provide several advantages including direct memory access, returning multiple values from functions, reducing storage space and complexity, and allowing dynamic memory allocation. The document outlines various uses of pointers, their characteristics, types including null, void, and wild pointers, and arithmetic operations that can be performed on pointers like addition, subtraction, incrementing and decrementing. It also discusses pointers to arrays and how pointers allow implementing data structures.

Uploaded by

Vekariya Kartik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Ch-3 Pointers

Introduction:

 In C programming language we use normal variable to


store user data values. When we declare a variable the
compiler allocates required memory with the specified
names.
 Pointer is a special type of variable used to store the
memory location address of variable.

 Uses of Pointers:

1. To pass argument by reference.


2. To access array statements.
3. To return multiple values.
4. Dynamic memory allocation.
5. To implement data structure.
6. To do system level programming where memory
address are useful.

 Advantages of Pointers:

Pointers provide direct access to memory.


Pointers provide a way to return more than one value
to the function.
Reduces the storage space and complexity of the
program.
Reduces the execution time of the program.
Provides an alternate way to access array elements.
Pointers can be used to pass information back and
forth between the calling function and called
function.
Pointers allow us to perform dynamic memory
allocation and deallocation.
Pointer helps us to build complex data structures like
linked list, stack, queues, trees, graph, etc.
Pointers allow us to resize the dynamically allocated
memory block.
Address of objects can be extracted using pointers.

 Disadvantages of Pointers:

Uninitialized pointers might cause segmentation


fault.
Dynamically allocated block needs to be freed
explicitly. Otherwise, it would need to memory
leakage.
Pointers are slower than normal variables.
Is pointers are updated with incorrect values it might
lead to memory corruption.
 Characteristics of Pointers:

Pointers are special variable that store the memory


address instead of values like in usual variables.
Pointers always hold address as a whole number.
Pointers in C are always initialized to null. For
example int *ptr=null;
Null pointer symbol is “\0”
The (*) asterisk symbol is used to retrieve the value
of a variable; (&) ampersand symbol is used
retrieving the address of the variable.
If a C pointer is assigned to null value, then it points
nothing.
Only subtraction between pointers is allowed while
addition, division and multiplication operations are
not allowed.
The memory size of C pointers for a 16 bit system is
2 bytes.

 Significance of Pointers:

1) Pointers provide direct address to memory.


2) Pointers provide a way to return more than one value
to the functions.
3) Reduce the storage space and complexity of the
program.
4) Reduces the execution time of the program.
5) Provides an alternate way to access array elements.
6) Pointers can be used to pass information back and
forth between the calling function and called
function.
7) Pointers allow us to perform dynamic memory
allocation and deallocation.
8) Pointer helps us to build complex data structures like
linked list, stack, queues, trees, graph, etc.
9) Pointers allow us to resize the dynamically allocated
memory block.
10) Address of objects can be extracted using pointers.

 Types of Pointers:

1) Null Pointer: If we don’t initialize a pointer after


declaration then by default the pointer is null pointer.
We can also explicitly do this by assigning the
NULL value at the time of pointer declaration. This
method is useful when you do not assign any address
to the pointer.

Program:
#include<stdio.h>
#include<conio.h>
int main()
{
int *p=null;//p is null pointer
printf(“%d”,p);
return 0;
}

O/P:
0

2) Void Pointer: It is a generic pointer that doesn’t have


any datatype associated with it. The datatype of void
pointer can be any type and can be typecast to any
type.
Program:
#include<stdio.h>
#include<conio.h>
int main()
{
int *p;//p is a void pointer
*p=10;
printf(“%d”,sizeof(p));
return 0;
}

O/P:
8

3) Wild Pointer: Wild pointer are basically an


uninitialized pointer that points to arbitrary memory
location and may cause a program to crash or behave
badly.
Program:
#include<stdio.h>
#include<conio.h>
int main()
{
int *p;//p is a wild pointer
*p=10;
}

 Accessing the address of variable:

In C programming, we use the reference operator “&”


to access the address of variables. For example, to
access the address of variable “marks” we use “&
marks”. We use the following printf statement to
display memory location address of variable “marks”.
Example Code:
printf(“Address=%u”,&marks);
In the above example statement %u is used to display
the address of marks variable and the address of any
memory location is unsigned integer value.

 Declaring Pointers (Creating Pointers):

In C programming language declaration of pointer


variable is similar to the creation of normal variable
but the name is prefixed with * symbol. We use the
following Syntax to declare a pointer variable:
 datatype *pointerName;
 Example code:
int *ptr;
In the above example declaration the variable “ptr” is a
pointer variable address.
 Assigning Address to Pointer:

pointervariableName=&variableName;

 Accessing Variable Value using Pointer:

*pointerVariableName
Example Code:
#include<stdio.h>
#include<conio.h>
int main()
{
int a=10, *ptr;
clrscr();
ptr=&a;

printf(“Address of variable a=%u\n”, ptr”);


printf(“Value of variable a=%d\n”, *ptr”);
printf(“Address of variable ptr=%u\n”, ptr”);
}
O/P:
Address of variable a: 6356748
Value of variable a: 10
Address of variable ptr: 6356744

 Pointers Arithmetic Operations in C:

Pointer variables are used to store the address of


variables. Address of any variable is an unsigned
integer value i.e., it is a numerical value. So we can
perform arithmetic operations on pointer values.
But when we perform arithmetic operations on
pointer variable, the result depend on the amount of
memory required by the variable to which the
pointer is pointing. In the C programming language
we can perform the following arithmetic operations
on pointers:
1) Addition
2) Subtraction
3) Increment
4) Decrement
5) Comparison

1) Addition Operation on Pointer:

AddressAtPointer+(NumberToBeAdd+BytesofMemo
ryRequiredByDatatype)
Example Program:

void main()
{
int a, *intPtr;
floa b, *floatPtr;
double c, *double c;
clrscr();

intPtr=&a; //Assume address of a is 1000


doublePtr=&b; //Assume address of b is 2000
floatPtr=&c; //Assume address of c is 3000
intPtr=intPtr+3; //intPtr=1000+(3*2)
floatPtr=floatPtr+2; //floatPtr=2000+(2*4)
doublePtr=doublePtr+5; //doublePtr=3000+(5*6)
printf(“intPtr value: %u\n”,intPtr);
printf(“floatPtr value: %u\n”,floatPtr);
printf(“doublePtr value: %u\n”,doublePtr);

getch():
}

O/P:
intPtr value: 6356748
floatPtr value: 6356740
doublePtr value: 6356760

2) Subtraction Operation on Pointer:


AddressAtPointer-
(NumberToBeAdd*BytesofMemoryRequiredByDatat
ype)

Example Program:

void main()
{
int a, *intPtr;
floa b, *floatPtr;
double c, *double c;
clrscr();

intPtr=&a; //Assume address of a is 1000


doublePtr=&b; //Assume address of b is 2000
floatPtr=&c; //Assume address of c is 3000
intPtr=intPtr-3; //intPtr=1000-(3*2)
floatPtr=floatPtr-2; //floatPtr=2000-(2*4)
doublePtr=doublePtr-5; //doublePtr=3000-(5*6)
printf(“intPtr value: %u\n”,intPtr);
printf(“floatPtr value: %u\n”,floatPtr);
printf(“doublePtr value: %u\n”,doublePtr);

getch():
}

O/P:
intPtr value: 6356724
floatPtr value: 6356724
doublePtr value: 6356778

3) Increment & Decrement Operation on Pointer:

The increment operation on pointer variable is


calculated as follows:
AddressAtPointer+(NumberofBytesRequiredByDat
atype)
Example Program:

void main()
{
int a, *intPtr;
floa b, *floatPtr;
double c, *double c;
clrscr();

intPtr=&a; //Assume address of a is 1000


doublePtr=&b; //Assume address of b is 2000
floatPtr=&c; //Assume address of c is 3000
intPtr++; //intPtr=1000+2
floatPtr++; //floatPtr=3000+6
printf(“intPtr value: %u\n”,intPtr);
printf(“floatPtr value: %u\n”,floatPtr);

getch():
}

O/P:
intPtr value: 6356724
floatPtr value: 6356724

The decrement operation on pointer variable is


calculated as follows:
AddressAtPointer-
(NumberofBytesRequiredByDatatype)

4) Comparison of Pointer:

The comparison operation is performed between the


pointers of same datatype only. In C programming
language, we can use all comparison operators
(relational operators) with pointers.
We can’t perform multiplication and division
operations on pointers.

 Array of Pointers:

Before we understand the concept of arrays of


pointers, let us consider the following examples
which uses an array of three integers:
Example Program:
#include <stdio.h>
#include<conio.h>
const intMAX=3;
int main()
{
int var[] = {10, 100, 200};
int i,*ptr[MAX];
for (int i = 0; i < MAX; i++)
{
p[i]= &var[i]; //assign the address of integer
}

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


{
printf("Value of var[%d]= %d\n", i,*ptr[i]);
}

return 0;
}

O/P:
Value of var[0]=10
Value of var[1]=100
Value of var[2]=200

You can also use an array of pointers to character


to store a list of string as follows;
#include <stdio.h>
#include<conio.h>
const intMAX=4;
int main()
{
char *names[] = {
“Zara Ali”;,
“Hina Ali”;,
“Nuba Ali”;,
“Sara Ali”;
};
int i=0;
for (int i = 0; i < MAX; i++)
{
printf("Value of names[%d]= %s\n",
i,names[i]);
}

return 0;
}

O/P:
Value of names[0]= Zara Ali
Value of names[1]= Hina Ali
Value of names[2]= Nuha Ali
Value of names[3]= Sara Ali

 Pointers to Pointers in C:

In the C programming language, we have pointers to


store the address of variables of any datatype. A
pointer variable can store the address of a normal
variable. C Programming Language also provides a
pointer variable to store the address of another
pointer variable. This type of pointer variable is
called a pointer to pointer variable. Sometimes we
also call it a double pointer. We use the following
syntax for creating pointer to pointer:
Datatype **pointerName;
Example Program:
int **ptr;

 Most Important Points to be


Remembered:

1) Address of normal variable we use single pointer


variable.
2) To store the address of single pointer variable we use
double pointer variable.
3) To store the address of double pointer variable we use
triple pointer variable.
4) Similarly the same for remaining pointer variables
also..

Example Program:
#include<stdio.h>
#include<conio.h>
int main()
{
int a;
int *ptr1;
int **ptr2;
int ***ptr3;

ptr1=&a;
ptr2=&ptr1;
ptr3=&ptr2;
printf(“Address of normal variable ‘a’=%u\n”,
ptr1”);
printf(“Address of pointer variable
‘*ptr1’=%u\n”, ptr2”);
printf(“Address of pointer variable
‘**ptr2’=%u\n”, ptr3”);

return 0;
}

O/P:
Address of normal variable ‘a’= 6356744
Address of pointer variable ‘*ptr1’= 6356740
Address of pointer variable ‘**ptr2’= 6356736
Ch-3 Practicals:

P-3.1: Write a C program to print address of variable using pointers

#include<stdio.h>
#include<conio.h>
int main()
{
int num = 10;
int *ptr = &num;
clrscr();

printf("The value of variable num is %d\n", num);


printf("The address of variable ptr is %p\n", &ptr);

return 0;
}

O/P:
The value of variable num is 10
The address of variable ptr is 0x7fff5fbff7d8

P-3.2: Write a C program to access element using pointers

#include <stdio.h>
#include<conio.h>
int main()

int *a,b;
clrscr();
printf("Enter any value: ");
scanf("%d",&b);

a=&b; //pointer initialization


printf("a=%d\n", *a); //pritning the value

return 0;
}

O/P:
Enter any value: 45
a= 45

P-3.3: Write a C program to read and print array elements using pointers

#include <stdio.h>
#include<conio.h>
int main()
{
int arr[5];
int *ptr = arr; // initialize pointer to first element of array
clrscr();

printf("Enter the values of the array:\n");


for (int i = 0; i < 5; i++)
{
scanf("%d", ptr+i);
}

printf("Printing array elements using pointer:\n");


for (int i = 0; i < 5; i++)
{
printf("arr[%d] = %d\n", i, *(ptr+i));
}

return 0;
}

O/P:
Enter the values of the array:
10
20
30
40
50
Printing array elements using pointer:
arr[0] = 10
arr[1] = 20
arr[2] = 30
arr[3] = 40
arr[4] = 50

P-3.4: Write a C program to read given variables using pointer to pointer

#include <stdio.h>
#include<conio.h>
int main()
{
int a;
int *b;
int **c;
clrscr();

b = &a; // b points to a
c = &b; // c points to b

printf("Enter a value for a: ");


scanf("%d", *c); // read value into num using ptr

printf("The value of a is %d\n", a);

return 0;
}

O/P:
Enter a value for a: 23
The value of a is 23
P-3.5: Write a C program to make a void pointer

#include <stdio.h>
#include<conio.h>
int main()
{
void *p=NULL; //p is a void pointer
clrscr();

printf("%d", sizeof(p));
return 0;
}

O/P:
8

P-3.6: Write a C program to find out length of string using pointer

#include <stdio.h>
#include<conio.h>
int main()
{
char str[100];
char *ptr;
int len = 0;
clrscr();

printf("Enter a string: ");


gets(str);

ptr = str; // ptr points to the first character of str

while (*ptr != '\0')// iterate through the string using ptr


{
len++;
ptr++;
}
printf("The length of the string is %d\n", len);

return 0;
}

O/P:
Enter a string: Haashim Mirza
The length of the string is 13

P-3.7: Write a C program to find out the sum of array element using
pointer

#include <stdio.h>
#include<conio.h>
int main()
{
int arr[5] = {1, 2, 3, 4, 5};
int *ptr;
int sum = 0;
clrscr();

ptr = arr; // ptr points to the first element of arr

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


{
sum += *ptr;
ptr++;
}

printf("The sum of the array is %d\n", sum);

return 0;
}

O/P:
The sum of the array is 15
P-3.8: Write a C program to give solution of a quadratic equation using
pointer

-b±√b2 -4ac
//Quadratic Equation Formula: x=
2a
#include <stdio.h>
#include<conio.h>
#include <math.h>
int main()
{
float a, b, c, r1, r2, d;
clrscr();
printf("Enter the values of a, b, and c: ");
scanf("%f %f %f", &a, &b, &c);

2
d = b * b - 4 * a * c; // d(Determinant)=-b±√𝑏 − 4𝑎𝑐⁄2
if (d > 0) //D>0 the roots are real and unequal
{
r1 = (-b + sqrt(d)) / (2 * a);
r2 = (-b - sqrt(d)) / (2 * a);
printf("The real roots are: %f and %f", r1, r2);
}
else if (d == 0) //D=0 the roots are real and equal
{
r1 = r2 = -b / (2 * a);
printf("The roots are equal: %f and %f", r1, r2);
}
else //D<0 the roots are imaginary
{
printf("The roots are imaginary");
}

return 0;
getch();
}
O/P:
Enter the values of a, b, and c: 1 1 4
The roots are imaginary

P-3.9: Write a C program to illustrate the use of array of pointer

#include <stdio.h>
#include<conio.h>
int main() {
char *names[] = {"Haashim", "Ayan", "Charlie", "Zaid", "Eve"};
int i;
clrscr();

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


{
printf("Name %d: %s\n", i+1, names[i]);
}

return 0;
}

O/P:

Name 1: Haashim
Name 2: Ayan
Name 3: Charlie
Name 4: Zaid
Name 5: Eve

You might also like