0% found this document useful (0 votes)
3 views

FCS_Module-4_Notes[Pointers]

Module-4 covers pointers and arrays in C programming, explaining the concept of pointers, their advantages and disadvantages, and how to declare and use them. It includes examples of pointer arithmetic, passing arguments to functions using pointers, and the use of pointers with arrays and strings. Additionally, it discusses null pointers, pointers to multidimensional arrays, and pointers to pointers (double pointers).

Uploaded by

daksh.yagya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

FCS_Module-4_Notes[Pointers]

Module-4 covers pointers and arrays in C programming, explaining the concept of pointers, their advantages and disadvantages, and how to declare and use them. It includes examples of pointer arithmetic, passing arguments to functions using pointers, and the use of pointers with arrays and strings. Additionally, it discusses null pointers, pointers to multidimensional arrays, and pointers to pointers (double pointers).

Uploaded by

daksh.yagya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Module-4: Pointers & Arrays

Introduction to Pointers:
A pointer is a variable that holds the address of another variable. The pointer
variable contains only the address of the referenced variable not the value
stored at that address.
Advantages of using pointers are as follows
1. Pointers are more efficient in handling arrays and data tables
2. Pointers are used with function to return multiple values
3. Pointers allow C to support dynamic memory management
4. Pointers provide an efficient tool for manipulating dynamic data structures
such as structures, linked list, stacks, queues, trees etc
5. Pointers reduce length and complexity of program
6. Pointers reduce program execution time and saves data storage space in
memory
Disadvantages of pointers
1. Program may crash if sufficient memory is not available at run time to store
pointers.
Pointer uses two basic operators

1. The address operator (&): It gives address of an object

2. The indirection operator (*): It is used to accesses the object the pointer
points to.

Declaring a Pointer:

• A pointer provides access to a variable by using the address of that variable.

The general syntax: data_type *ptr_name;

Data type: It specifies the type of the pointer variable that you want to declare
like (int, float, char, double or void)

* (Asterisk): tells the compiler that we are creating a pointer variable and
ptr_name specifies the name of the pointer variable.

Example:
int *p; // declares a pointer variable p of integer type
float *temp; //declares a pointer variable temp of float data type Now
consider,
example:
int x = 10;
int *ptr;
ptr = &x;

Dr Santhosh Kumar S, Jain University. 1


Module-4: Pointers & Arrays

• Now, since x is an integer variable, it will be allocated 2 bytes.

• Assuming that the complier assigns it memory locations 1003 and 1004, we
say the value of x=10 and address of x is equal to 1003. We can dereference
a pointer, i.e, refer to the value of the variable to which it points, by using ‘*’
operator as in *ptr.

Example: Program of usage of pointer variable


#include<stdio.h>
void main()
{
int x = 99;
int *ptr; // Declare a pointer
ptr = &x; // Assign the value to pointer
printf("Value of ptr = %d\n", *ptr);
printf("Address of ptr =%p\n", ptr);
}
Output:
Value of ptr = 99
Address of ptr =0x7ffdba4e00e4
Also note that it is not necessary that the pointer variable will point to the
same variable throughout the program. It can point to any variable as long as
the data type of the pointer variable it points to.

The following code illustrates this concept


# include<stdio.h>
void main()
{
int a=3, b=5;
int *pnum;

Dr Santhosh Kumar S, Jain University. 2


Module-4: Pointers & Arrays

pnum = &a;
printf("\n a = %d\n",*pnum); pnum = &b;
printf("b = %d\n",*pnum);
}
Output:
a=3
b=5

Using the address of (&) operator:

• A computer uses memory to store the instructions of different programs and


the values of different variables.

• Since memory is a sequential collection of storage cells, each cell has an


address.

• When we declare a variable, the operating system allocates memory according to


the size of the data type of that variable.

• In this memory location, the value of the variable is stored.

Example: int a=100;

This statement requests the operating system to allocate two bytes of space in
memory and stores 100 in that location.

By using the address of (&) operator, you can determine the address of a variable

Pointer Expressions and Pointer Arithmetic


Pointer variables can also be used in expressions.
Ex: int num1=2, num2= 3, sum=0, mul=0, div=1;
int *ptr1, *ptr2;
ptr1 = &num1, ptr2 = &num2;
sum = *ptr1 + *ptr2;

Dr Santhosh Kumar S, Jain University. 3


Module-4: Pointers & Arrays

mul = sum * *ptr1;


*ptr2 +=1;
div = 9 + *ptr1/*ptr2 - 30;

• We can add integers to or subtract integers from pointers as well as to subtract


one pointer from the other.

• We can compare pointers by using relational operators in the expressions. For


example p1 > p2 , p1==p2 and p1!=p2 are all valid in C.

• When using pointers, unary increment (++) and decrement (--) operators have
greater precedence than the dereference operator (*). Therefore, the expression

• *ptr++ is equivalent to *(ptr++). So the expression will increase the value of ptr
so that it now points to the next element.

• In order to increment the value of the variable whose address is stored in ptr,
write (*ptr)++.

Summarize the rules of pointers:

• A pointer variable can be assigned the address of another variable (of the same
type).

• A pointer variable can be assigned the value of another pointer variable (of the
same type). A pointer variable can be initialized with a null value.

• Prefix or postfix increment and decrement operators can be applied on a pointer


variable.

• An integer value can be added or subtracted from a pointer variable.


• A pointer variable can be compared with another pointer variable of the same
type using relational operators.

• A pointer variable cannot be multiplied by a constant.

• A pointer variable cannot be added to another pointer variable.

Dr Santhosh Kumar S, Jain University. 4


Module-4: Pointers & Arrays

• WAP to add 2 floating point numbers using pointers.


# include<stdio.h>
void main()
{
float num1,num2,sum=0.0;
float *pnum1=&num1,*pnum2=&num2,*psum=&sum;
printf("Enter 2 numbers: ");
scanf("%f,%f",pnum1,pnum2);
*psum=*pnum1+*pnum2;
printf("%f + %f = %f",*pnum1,*pnum2,*psum);
}
Output:
Enter 2 numbers: 3.2,2.3
3.200000 + 2.300000 = 5.500000

WAP to test whether a number is positive, negative or equal to zero


#include<stdio.h>
void main()
{
int num,*pnum=&num;
printf("Enter any number: ");
scanf("%d",pnum);
if(*pnum>0)
printf("The number is positive");
else if(*pnum<0)
printf("The number is negative");
else
printf("The number is equal");
}
Output:
Enter any number: 2
The number is positive

Dr Santhosh Kumar S, Jain University. 5


Module-4: Pointers & Arrays

WAP to print all even numbers from m to n.


#include<stdio.h>
void main()
{
int m,*pm=&m; int n,*pn=&n;
printf("Enter the starting and ending limit: ");
scanf("%d,%d",pm,pn);
while(*pm<=*pn)
{
if(*pm%2==0)
printf("%d is even\n",*pm); (*pm)++;
}}
Output:
Enter the starting and ending limit: 0,10 0 is even
2 is even
4 is even
6 is even
8 is even
10 is even

Null Pointers
A null pointer which is a special pointer value that is known not to point
anywhere. This means that a NULL pointer does not point to any valid memory
address.
To declare a null pointer we may use the predefined constant NULL,
int *ptr = NULL;
we can always check whether a given pointer variable stores address of some
variable or contains a null by writing,
if ( ptr == NULL)
{
Statement block;
}

Dr Santhosh Kumar S, Jain University. 6


Module-4: Pointers & Arrays

• Null pointers are used in situations if one of the pointers in the program points
somewhere some of the time but not all of the time.

• In such situations it is always better to set it to a null pointer when it doesn't


point anywhere valid, and to test to see if it's a null pointer before using it.

• (int*)gp: This part involves type casting. It's casting the pointer gp to a pointer to
an integer (int*).

• *(int*)gp: Finally, it dereferences the casted pointer, retrieving the value stored
at the memory location pointed to by gp, but interpreting it as an integer.

PASSING ARGUMENTS TO FUNCTION USING POINTERS


• The calling function sends the addresses of the variables and the called
function must declare those incoming arguments as pointers.
• In order to modify the variables sent by the caller, the called function must
dereference the pointers that were passed to it.
• Thus, passing pointers to a function avoid the overhead of copying data from one
function to another.

WAP to add 2 integers using functions.


#include<stdio.h>
void sum ( int *a, int *b, int *t); int main()
{ int num1, num2, total;
printf("\n Enter two numbers : ");
scanf("%d,%d", &num1, &num2);
sum(&num1, &num2, &total);
printf("\n Total = %d", total);
return 0;
}
void sum ( int *a, int *b, int *t)
{ *t = *a + *b;
return;
}
Output: Enter two numbers : 2,3 Total = 5

Dr Santhosh Kumar S, Jain University. 7


Module-4: Pointers & Arrays

WAP to find the largest of 3 integers using functions.


#include<stdio.h>
void large( int *a, int *b, int *c, int *lar);
int main()
{ int num1, num2, num3, big;
printf("\n Enter 3 numbers : ");
scanf("%d,%d,%d", &num1, &num2, &num3);
large(&num1, &num2, &num3, &big);
return 0;
}
void large( int *a, int *b, int *c, int *lar)
{
if(*a>*b && *a>*c)
*lar=*a;
else if(*b>*a && *b>*c)
*lar=*b;
else
*lar=*c;
printf("The largest number is %d",*lar);
}

Output:

Enter 3 numbers : 2,5,6 The largest number is 6

Pointer to an Array:
A pointer to an array is a pointer that points to the whole array instead of the first
element of the array. It considers the whole array as a single unit instead of it being a
collection of given elements.
Syntax: type(*ptr)[size];
where,
• type: Type of data that the array holds.

Dr Santhosh Kumar S, Jain University. 8


Module-4: Pointers & Arrays

• ptr: Name of the pointer variable.


• size: Size of the array to which the pointer will point
Example: int (*ptr)[10];
Here ptr is pointer that points to an array of 10 integers.
Demonstrate the use pf pointer to an array in C and also highlights the difference
between the pointer to an array and pointer to the first element of an array.
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int *p1;
int(*p2)[5];
p1 = arr;
p2 = &arr;
printf("p1 = %p\n", p1);
printf("*p2 = %p\n\n", *p2);
p1++;
p2++;
printf("p1 = %p\n", p1);
printf("*p2 = %p", p2);
return 0;
}
Pointer to Multidimensional Arrays:
To define a pointer to a 2D array, both the number of rows and columns of the array must
be specified in the pointer declaration.
Syntax: type *(ptr)[row][cols]
#include <stdio.h>
int main() {
int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};
int (*ptr)[2][3] = &arr;
for (int i = 0; i < 2; i++) {

Dr Santhosh Kumar S, Jain University. 9


Module-4: Pointers & Arrays

for (int j = 0; j < 3; j++) {


printf("%d ", (*ptr)[i][j]);
}
printf("\n");
}
return 0;
}
Output:
123
456

Character Pointers and Functions:


A character pointer stores the address of a character type or address of the first character
of a character array (string). Character pointers are very useful when we are working to
manipulate the strings.
There is no string data type in C. An array of "char" type is considered as a string.
Hence, a pointer of a char type array represents a string. This char pointer can then be
passed as an argument to a function for processing the string.

Declaring a Character Pointer


A character pointer points to a character or a character array. To declare a character
pointer, use the following syntax:
char *pointer_name;
Initializing a Character Pointer
After declaring a character pointer, we need to initialize it with the address of a character variable.
If there is a character array, we can simply initialize the character pointer by providing the name
of the character array or the address of the first elements of it
char *pointer_name = &char_variable;

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

Dr Santhosh Kumar S, Jain University. 10


Module-4: Pointers & Arrays

char x = 'P';
char arr[] = "Jain";
char *ptr_x = &x;
char *ptr_arr = arr;
printf("Value of x : %c\n", *ptr_x);
printf("Value of arr: %s\n", ptr_arr);
return 0;
}
Output: Value of x : P
Value of arr: Jain

A string is declared as an array as follows − char arr[] = "Hello";


The string is a NULL terminated array of characters. The last element in the above array is
a NULL character (\0).
Declare a pointer of char type and assign it the address of the character at the 0th position as
follows
char *ptr = &arr[0];

Pointer to Pointer:
A pointer to pointer which is also known as a double pointer in C is used to
store the address of another pointer.
A "pointer to a pointer" is a form of multiple indirections or a chain of
pointers.
In "pointer to a pointer", the first pointer contains the address of the second
pointer, which points to the location that contains the actual value as shown
below –

Dr Santhosh Kumar S, Jain University. 11


Module-4: Pointers & Arrays

The declaration of a pointer to pointer (double pointer) is as follows:


int **var;
#include <stdio.h>
int main()
{
int var = 789;
int* ptr2;
int** ptr1;
ptr2 = &var;
ptr1 = &ptr2;
printf("Value of var = %d\n", var);
printf("Value of var using single pointer = %d\n", *ptr2);
printf("Value of var using double pointer = %d\n", **ptr1);
return 0;
}
Output:
Value of var = 789
Value of var using single pointer = 789
Value of var using double pointer = 789
Uses of pointer to pointers in C:
• They are used in the dynamic memory allocation of multidimensional arrays.
• They can be used to store multilevel data such as the text document
paragraph, sentences, and word semantics.
• They are used in data structures to directly manipulate the address of the
nodes without copying.
• They can be used as function arguments to manipulate the address stored in
the local pointer

Dr Santhosh Kumar S, Jain University. 12


Module-4: Pointers & Arrays

Initialization of Pointer Arrays:

A pointer variable can be initialized at the time of declaration, by assigning it the address
of an existing variable.
int x = 10;
int *y = &x;
Example:
#include <stdio.h>
int main(){
int a = 10, b = 20, c = 30;
int *ptr[3] = {&a, &b, &c};
for (int i = 0; i < 3; i++){
printf("ptr[%d]: address: %d value: %d\n", i, ptr[i], *ptr[i]);
}
return 0;
}
Output:
ptr[0]: address: 6422040 value: 10
ptr[1]: address: 6422036 value: 20
ptr[2]: address: 6422032 value: 30

Pointers to functions:

A pointer to a function point to the address of the executable code of the function. Use
pointers to call functions and to pass functions as arguments to other functions.
It holds the base address of function definition in memory.
Syntax: datatype (*pointername) ();

Example:

#include <stdio.h>
void show(int* p){
(*p)++;
}

Dr Santhosh Kumar S, Jain University. 13


Module-4: Pointers & Arrays

int main(){
int* ptr, a = 20;
ptr = &a;
show(ptr);
printf("%d", *ptr);
return 0;
}

Application of Pointers

• Arrays and Strings:

Pointers can be used to traverse and manipulate arrays and strings more
efficiently.

• Function Pointers:

Pointers to functions allow you to create arrays of functions, pass functions


as arguments to other functions, or return functions from functions.

• Structures:

Pointers can be used to work with structures more efficiently, especially


when dealing with large structures.

• File Handling:

Pointers are used in file handling operations, enabling efficient reading and
writing of data to files.

• Efficient Parameter Passing:

Passing pointers to functions instead of passing large data structures can


be more efficient in terms of both time and space.

• Dynamic Data Structures:

Pointers are crucial in implementing dynamic data structures such as trees


and graphs.

• Callback Functions:

Pointers to functions are often used for implementing callback mechanisms,


where a function can be passed as an argument to another function.

Dr Santhosh Kumar S, Jain University. 14


Module-4: Pointers & Arrays

Command line arguments:

The arguments passed from command line are called command line arguments. These
arguments are handled by main () function.
Syntax: int main(int argc, char *argv[ ] )

Where,
argc counts the number of arguments. It counts the file name as the first argument.
The argv[] contains the total number of arguments. The first argument is the file name
always
Example:
#include <stdio.h>
void main(int argc, char *argv[] ) {
printf("Program name is: %s\n", argv[0]);
if(argc < 2){
printf("No argument passed through command line.\n");
}
else{
printf("First argument is: %s\n", argv[1]);
}
}
Run above the program using Windows from command line is as follows:
program.exe hello
Output:
Program name is: program
First argument is: hello

Dr Santhosh Kumar S, Jain University. 15


Module-4: Strings and Pointers

You might also like