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

UNIT 4 C Language Pointers

A full lesson of C language Pointers

Uploaded by

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

UNIT 4 C Language Pointers

A full lesson of C language Pointers

Uploaded by

abdulwahid.a1707
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

C Pointers

The pointer in C language is a variable which stores the address of another variable. This variable can
be of type int, char, array, function, or any other pointer.
Consider the following example to define a pointer which stores the address of an integer.
int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type
integer.
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known as indirection
pointer.
int *a;//pointer to int
char *c;//pointer to char
Pointer Example
An example of using pointers to print the address and the value is given below.

In the above figure, pointer variable stores the address of number variable is fff4. The value of
number variable is 50. But the address of pointer variable p is aaa3.

Example:
#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
Advantages of pointer

1. Pointers save memory space.


2. Execution time with pointers is faster because data are manipulated with the
address, that is, direct access to memory location.
3. Memory is accessed efficiently with the pointers. The pointer assigns and
releases the memory as well. Hence it can be said the Memory of pointers is
dynamically allocated.
4. Pointers are used with data structures. They are useful for representing two-
dimensional and multi-dimensional arrays.
5. An array, of any type, can be accessed with the help of pointers, without
considering its subscript range.
6. Pointers are used for file handling.
7. Pointers are used to allocate memory dynamically.

Usage of pointer
There are many applications of pointers in c language.
1) Dynamic memory allocation
In c language, we can dynamically allocate memory using malloc() and calloc() functions where the
pointer is used.
2) Arrays, Functions, and Structures
Pointers in c language are widely used in arrays, functions, and structures. It reduces the code and
improves the performance.

Address Of (&) Operator


The address of operator '&' returns the address of a variable. But, we need to use %u to display the
address of a variable.
#include<stdio.h>
int main()
{
int number=50;
printf("value of number is %d, address of number is %u",number,&number);
return 0;
}
Output
value of number is 50, address of number is fff4
Different Types of Pointers:
There are majorly four types of pointers, they are:
 Null Pointer
 Void Pointer
 Wild Pointer
 Dangling Pointer
Null Pointer:

If you assign a NULL value to a pointer during its declaration, it is called Null Pointer.
Syntax:
int *var = NULL;
Example:
#include<stdio.h>
int main()
{
int *var = NULL;
printf(“var=%d”,*var);
}

Void Pointer:

When a pointer is declared with a void keyword, then it is called a void pointer. To print the value of
this pointer, you need to typecast it.
Syntax:
void *var;

Example:
#include<stdio.h>
int main()
{
int a=2;
void *ptr;
ptr= &a;
printf("After Typecasting,
a = %d", *(int *)ptr);
return 0;
}
Wild Pointer:

A wild pointer is only declared but not assigned an address of any variable. They are very tricky, and
they may cause segmentation errors.
Example:
#include<stdio.h>
int main()
{
int *ptr;
printf(“ptr=%d”,*ptr);
return 0;
}

Dangling Pointer

 Suppose there is a pointer p pointing at a variable at memory 1004. If you deallocate this memory,
then this p is called a dangling pointer.
 You can deallocate a memory using a free() function.
Example:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr=(int *)malloc(sizeof(int));
int a=5;
ptr=&a;
free(ptr);
//now this ptr is known as dangling pointer.
printf(“After deallocating its memory *ptr=%d”,*ptr);
return 0;
}
Pointer arithmetic:
 Increment: You can use this operator to jump from one index to the next index in an array.
Syntax:
ptr++;

Example:
#include <stdio.h>
int main() {
int arr[3] = {50, 150, 200};
int *ptr;
ptr = arr;
for (int i = 0; i < 3; i++)
{
printf(“Value of *ptr = %d\n”,*ptr);
printf(“Address of *ptr = %d\n”,ptr);
ptr++;
}

 Decrement: You can use this operator to jump from one index to the previous index in an
array.
Syntax:
Ptr--;
Example:
#include<stdio.h>
int main()
{
int arr[3]={50, 150, 200};
int *ptr;
ptr = &arr[2];
for (int i=0;i<3;i++)
{
printf("Value of *ptr = %d\n", *ptr);
printf("Address of *ptr = %d\n\n", ptr);
ptr--;
}
}

 Integers added to a Pointer: You can use this operator to jump from one index to the next ith
index in an array.
Syntax:
ptr+=i; // where ‘i’ is an integer

Example:
#include <stdio.h>
int main() {
int arr[5] = {10, 100, 200, 300, 500};
int *ptr;
ptr = &arr[0];
for (int i = 0; i < 5; i++) {
printf("Value of *ptr = %d\n", *ptr);
printf("Address of *ptr = %d\n\n", ptr);
ptr=ptr+2;
}
}
 Integers Subtracted from a Pointer: You can use this operator to jump from one index to the
previous ith index in an array.
Syntax:
ptr-=i; // where ‘i’ is an integer

Example:
#include <stdio.h>
int main() {
int arr[5] = {10, 100, 200, 300, 500};
int *ptr;
ptr = &arr[4];
for (int i = 0; i<5; i++)
{
printf("Value of *ptr = %d\n", *ptr);
printf("address of *ptr = %d\n\n", ptr);
ptr-=2;
}
}
Precedence:
Operators * and & are given the same priorities as unary operators (increment++, decrement--).
The unary operators *, &, ++, - are evaluated from right to left in the same expression.
 If a P points to an X variable, then you can interchange X with *P.

Equivalent
Expression
Expression

Y=X+1 Y=*P+1

X=X+10 *P=*P+10

X+=2 *P+=2

++X ++*P

X++ (*P)++

Pointer to an Array in C
Pointers to an array points the address of memory block of an array variable.
The following is the syntax of array pointers.
datatype *variable_name[size];
Here,
datatype − The datatype of variable like int, char, float etc.
variable_name − This is the name of variable given by user.
size − The size of array variable.
The following is an example of array pointers.
Example
#include <stdio.h>
int main () {
int *arr[3];
int *a;
printf( "Value of array pointer variable : %d", arr);
printf( "Value of pointer variable : %d", &a);
return 0;
}
Output
Value of array pointer variable : 1481173888
Value of pointer variable : 1481173880
In the above program, an array pointer *arr and an integer *a are declared.
int *arr[3];
int *a;
The addresses of these pointers are printed as follows −
printf("Value of array pointer variable : %d", arr);
printf("Value of pointer variable : %d", &a);

Structure:
Structure in C is a user-defined data type that enables us to store the collection of different data
types. Each element of a structure is called a member.
The struct keyword is used to define the structure. Let's see the syntax to define the structure in c.
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
The example to define a structure for an entity employee in c.
struct employee
{
int id;
char name[20];
float salary;
};
The following image shows the memory allocation of the structure employee that is defined in the
above example.
Here, struct is the keyword; employee is the name of the structure; id, name, and salary are the
members or fields of the structure.

Declaring structure variable:


We can declare a variable for the structure so that we can access the member of the structure easily.
There are two ways to declare structure variable:
1. By struct keyword within main() function
2. By declaring a variable at the time of defining the structure.
1st way:
Let's see the example to declare the structure variable by struct keyword. It should be declared within
the main function.
struct employee
{ int id;
char name[50];
float salary;
};
Now write given code inside the main() function.
1. struct employee e1, e2;
The variables e1 and e2 can be used to access the values stored in the structure.
2nd way:
Let's see another way to declare variable at the time of defining the structure.
struct employee
{ int id;
char name[50];
float salary;
}e1,e2;
Accessing members of the structure
There are two ways to access structure members:
1. By . (member or dot operator)
2. By -> (structure pointer operator)
C Structure example
Let's see a simple example of structure in C language.
#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
}e1; //declaring e1 variable for structure
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
Output:
employee 1 id : 101
employee 1 name : Sonoo Jaiswal
Let's see another example of the structure in C language to store many employees information.
#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
float salary;
}e1,e2; //declaring e1 and e2 variables for structure
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
e1.salary=56000;
//store second employee information
e2.id=102;
strcpy(e2.name, "James Bond");
e2.salary=126000;
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
printf( "employee 1 salary : %f\n", e1.salary);

//printing second employee information


printf( "employee 2 id : %d\n", e2.id);
printf( "employee 2 name : %s\n", e2.name);
printf( "employee 2 salary : %f\n", e2.salary);
return 0;
}
Output:
employee 1 id : 101
employee 1 name : Sonoo Jaiswal
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000

Operations performed on structure variable:

The only operation that is allowed on structure variables is the assignment operation . Two
variables of the same structure can be copied similar to ordinary variables.

If P1 and P2 are variables of struct P, then P1 values can be assigned to P2 as

P2=P1;

where values of P1 will be assigned to P2 member by member.

Example program illustrating operation on structure variables:

#include<stdio.h>
#include<string.h>
struct student
{
int rno;
char name[10];
int marks,age;
};
void main()
{
//assigning values to structure variable s1 using initalization
struct student s1={2,"Gandhi",89,18};
struct student s2;
s2=s1;
printf("\nDetails of student 1:\n");
printf("\n roll number: %d",s1.rno);
printf("\n name :%s",s1.name);
printf("\n marks: %d",s1.marks);
printf("\n age: %d",s1.age);
printf("\n\n");
printf("Details of student 2:\n");
printf("\n roll number: %d",s2.rno);
printf("\n name :%s",s2.name);
printf("\n marks: %d",s2.marks);
printf("\n age: %d",s2.age);
}

Output:

Note: C does not permit any logical operations on structure variables.

C Array of Structures:

Consider a case, where we need to store the data of 5 students. We can store it by using the structure
as given below.
#include<stdio.h>
struct student
{
char name[20];
int id;
float marks;
};
void main()
{
struct student s1,s2,s3;
printf("Enter the name, id, and marks of student 1 ");
scanf("%s %d %f",s1.name,&s1.id,&s1.marks);
printf("Enter the name, id, and marks of student 2 ");
scanf("%s %d %f",s2.name,&s2.id,&s2.marks);
printf("Enter the name, id, and marks of student 3 ");
scanf("%s %d %f",s3.name,&s3.id,&s3.marks);
printf("Printing the details....\n");
printf("%s %d %f\n",s1.name,s1.id,s1.marks);
printf("%s %d %f\n",s2.name,s2.id,s2.marks);
printf("%s %d %f\n",s3.name,s3.id,s3.marks);
}
Output
Enter the name, id, and marks of student 1 James 90 90
Enter the name, id, and marks of student 2 Adoms 90 90
Enter the name, id, and marks of student 3 Nick 90 90
Printing the details....
James 90 90.000000
Adoms 90 90.000000
Nick 90 90.000000
In the above program, we have stored data of 3 students in the structure. However, the complexity of
the program will be increased if there are 20 students. In that case, we will have to declare 20
different structure variables and store them one by one. This will always be tough since we will have
to declare a variable every time we add a student. Remembering the name of all the variables is also a
very tricky task. However, c enables us to declare an array of structures by using which, we can avoid
declaring the different structure variables; instead we can make a collection containing all the
structures that store the information of different entities.
Array of Structures in C
An array of structures in C can be defined as the collection of multiple structures variables where
each variable contains information about different entities. The array of structures in C are used to
store information about multiple entities of different data types. The array of structures is also known
as the collection of structures.
Let's see an example of an array of structures that stores information of 5 students and prints it.
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main(){
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}
Output:
Enter Records of 5 students
Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz

Student Information List:


Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz
Union in C
Union can be defined as a user-defined data type which is a collection of different variables of
different data types in the same memory location.
The union can also be defined as many members, but only one member can contain a value at a
particular point in time.
Union is a user-defined data type, but unlike structures, they share the same memory location
In union, members will share the memory location. If we try to make changes in any of the member
then it will be reflected to the other member as well. Let's understand this concept through an
example.
union abc
{
int a;
char b;
}var;
int main()
{
var.a = 66;
printf("\n a = %d", var.a);
printf("\n b = %d", var.b);
}
In the above code, union has two members, i.e., 'a' and 'b'. The 'var' is a variable of union abc type. In
the main() method, we assign the 66 to 'a' variable, so var.a will print 66 on the screen. Since both 'a'
and 'b' share the memory location, var.b will print 'B' (ascii code of 66).
Deciding the size of the union
The size of the union is based on the size of the largest member of the union.
Let's understand through an example.
union abc{
int a;
char b;
float c;
double d;
};
int main()
{
printf("Size of union abc is %d", sizeof(union abc));
return 0;
}
As we know, the size of int is 4 bytes, size of char is 1 byte, size of float is 4 bytes, and the size of
double is 8 bytes. Since the double variable occupies the largest memory among all the four variables,
so total 8 bytes will be allocated in the memory. Therefore, the output of the above program would be
8 bytes.
Accessing members of union using pointers
We can access the members of the union through pointers by using the (->) arrow operator.
Let's understand through an example.
#include <stdio.h>
union abc
{
int a;
char b;
};
int main()
{
union abc *ptr; // pointer variable declaration
union abc var;
var.a= 90;
ptr = &var;
printf("The value of a is : %d", ptr->a);
return 0;
}
In the above code, we have created a pointer variable, i.e., *ptr, that stores the address of var variable.
Now, ptr can access the variable 'a' by using the (->) operator. Hence the output of the above code
would be 90.

You might also like