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

IP Unit-4 Notes

Pointers in C are variables that store the addresses of other variables of the same data type, allowing for efficient handling of arrays and structures, dynamic memory management, and function references. They can be declared, initialized, and dereferenced using specific operators, and can also point to other pointers. Understanding pointer arithmetic, null pointers, and their relationship with arrays is crucial for effective programming in C.

Uploaded by

nagabadramram708
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)
8 views24 pages

IP Unit-4 Notes

Pointers in C are variables that store the addresses of other variables of the same data type, allowing for efficient handling of arrays and structures, dynamic memory management, and function references. They can be declared, initialized, and dereferenced using specific operators, and can also point to other pointers. Understanding pointer arithmetic, null pointers, and their relationship with arrays is crucial for effective programming in C.

Uploaded by

nagabadramram708
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

POINTERS

Introduction
Definition:
Pointer is a variable that stores/hold address of another variable of same data type/ it is
also known as locator or indicator that points to an address of a value. A pointer is a derived data
type in C.

Benefit of using pointers

 Pointers are more efficient in handling Array and Structure.


 Pointer allows references to function and thereby helps in passing of function as
arguments to other function.
 It reduces length and the program execution time.
 It allows C to support dynamic memory management.

Declaration of Pointer
data_type* pointer_variable_name;

Example:

int* p;

Note: void type pointer works with all data types, but isn't used often.

Initialization of Pointer variable

Pointer Initialization is the process of assigning address of a variable to pointer variable.

Pointer variable contains address of variable of same data type

int a = 10 ;
int *ptr ; //pointer declaration
ptr = &a ; //pointer initialization
or,
int *ptr = &a ; //initialization and declaration together
Note: Pointer variable always points to same type of data.
float a;
int *ptr;

ptr = &a; //ERROR, type mismatch


Above statement defines, p as pointer variable of type int.
Pointer example:

As you can see in the above figure, pointer variable stores the address of number variable i.e.
fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

Reference operator (&) and Dereference operator (*)

& is called reference operator. It gives you the address of a variable. There is another
operator that gets you the value from the address, it is called a dereference operator (*).

Symbols used in pointer:

Symbol Name Description


& (ampersand sign) address of operator Determines the address of a
variable.
* (asterisk sign) indirection operator Accesses the value at the
address.

Dereferencing of Pointer

Once a pointer has been assigned the address of a variable. To access the value of
variable, pointer is dereferenced, using the indirection operator *.

int a,*p;

a = 10;

p = &a;

printf("%d",*p); //this will print the value of a.

printf("%d",*&a); //this will also print the value of a.

printf("%u",&a); //this will print the address of a.

printf("%u",p); //this will also print the address of a.

printf("%u",&p); //this will also print the address of p.


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:
#include <stdio.h>
#include <conio.h>
void main()
{
int number=50;
int *p;
clrscr();
p=&number;//stores the address of number variable
printf("Address of number variable is %x \n",&number);
printf("Address of p variable is %x \n",p);
printf("Value of p variable is %d \n",*p);
getch();
}

Output
Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50

Example:

#include <stdio.h> int main()


{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
/* display q's value using ptr variable */
printf("%d", *ptr);
return 0;
}
Output: 50
NULL Pointer
A pointer that is not assigned any value but NULL is known as NULL pointer. If you
don't have any address to be specified in the pointer at the time of declaration, you can assign
NULL value.
Or

It is always a good practice to assign a NULL value to a pointer variable in case you do
not have an exact address to be assigned. This is done at the time of variable declaration. A
pointer that is assigned NULL is called a null [Link] *p=NULL;

Note: The NULL pointer is a constant with a value of zero defined in several standard libraries/
in most the libraries, the value of pointer is 0 (zero)
Example:
The value of ptr is 0

Pointers for Inter‐Function Communication


Pointers to Pointers
Pointers can point to other pointers /pointer refers to the address of another pointer.
pointer can point to the address of another pointer which points to the address of a value

syntax of pointer to pointer:


int **p2;

Pointer to pointer example:

Let's see an example where one pointer points to the address of another pointer.

Example:
#include <stdio.h>
#include <conio.h>
void main()
{
int number=50;
int *p;//pointer to int

int **p2;//pointer to pointer


clrscr();
p=&number;//stores the address of number variable
p2=&p;
printf("Address of number variable is %x \n",&number);
printf("Address of p variable is %x \n",p);
printf("Value of *p variable is %d \n",*p);
printf("Address of p2 variable is %x \n",p2);
printf("Value of **p2 variable is %d \n",**p);
getch();
}
Output:
Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50

Arrays and Pointers:

When an array is declared, compiler allocates sufficient amount of memory to contain all
the elements of the array. Base address which gives location of the first element is also allocated
by the compiler.
Suppose we declare an array arr,
int arr[5]={ 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two byte, the five
element will be stored as follows

Here variable arr will give the base address,which is a constant pointer pointing to the
element, arr[0]. Therefore arr is containing the address of arr[0] i.e 1000.
arr is equal to &arr[0] // by default
We can declare a pointer of type int to point to the array arr.
int arr[5]={ 1, 2, 3, 4, 5 };
int *p; p = arr;
or p = &arr[0]; //both the statements are equivalent.
Now we can access every element of array arr using p++ to move from one element to another.
NOTE : You cannot decrement a pointer once incremented. p-- won't work.
Pointer to Array:
We can use a pointer to point to an Array, and then we can use that pointer to access the
array. Lets have an example,
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i=0; i<5; i++)
{
printf("%d", *p); p++;
}
In the above program, the pointer *p will print all the values stored in the array one by one. We
can also use the Base address (a in above case) to act as pointer and print all the values.

Relation between Arrays and Pointers:


Consider an array:
int arr[4];

In C programming, name of the array always points to address of the first element of an array. In
the above example, arr and &arr[0] points to the address of the first element.
&arr[0] is equivalent to arr
Since, the addresses of both are the same, the values of arr and &arr[0] are also the same.
arr[0] is equivalent to *arr (value of an address of the pointer)
Similarly,

&arr[1] is equivalent to (arr + 1) AND, arr[1] is equivalent to *(arr + 1).


&arr[2] is equivalent to (arr + 2) AND, arr[2] is equivalent to *(arr + 2).
&arr[3] is equivalent to (arr + 3) AND, arr[3] is equivalent to *(arr + 3).
.
&arr[i] is equivalent to (arr + i) AND, arr[i] is equivalent to *(arr + i).

Example: Program to find the sum of six numbers with arrays and pointers

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

int i, classes[6],sum = 0;
printf("Enter 6 numbers:\n");
for(i = 0; i < 6; ++i)
{
// (classes + i) is equivalent to &classes[i]
scanf("%d",(classes + i));
// *(classes + i) is equivalent to classes[i]
sum += *(classes + i);
}
printf("Sum = %d", sum); return 0;
}

Output
Enter 6 numbers:
2
3
4
5
3
4
Sum = 21

Pointer Arithmetic and Arrays


Pointer holds address of a value, so there can be arithmetic operations on the pointer
variable. There are four arithmetic operators that can be used on pointers:
 Increment(++)
 Decrement(--)
 Addition(+)
 Subtraction(-)
 Increment pointer:

1. Incrementing Pointer is generally used in array because we have contiguous memory in


array and we know the contents of next memory location.
2. Incrementing Pointer Variable Depends Upon data type of the Pointer variable.

The formula of incrementing pointer is given below:


new_address= current_address + i * size_of(data type)
Three rules should be used to increment pointer
Address + 1 = Address
Address++ = Address
++Address = Address
Pictorial Representation :

Data Older Address storedin Next Address stored in pointer after


Type pointer incrementing (ptr++)

int 1000 1002

float 1000 1004

char 1000 1001

Note :

For 32 bit int variable, it will increment to 2 byte.64 bit

For 64 bit int variable, it will increment to 4 byte.

Example:

#include <stdio.h>
void 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);
}
Output:
Address of p variable is 3214864300
After increment: Address of p variable is 3214864304

Decrement (--):
Like increment, we can decrement a pointer variable. formula of decrementing pointer
new_address= current_address - i * size_of(data type)
Example:
#include <stdio.h>
void 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 decrement: Address of p variable is %u \n",p);
}

Output:
Address of p variable is 3214864300
After decrement: Address of p variable is 3214864296

Addition (+):
We can add a value to the pointer variable. formula of adding value to pointer
new_address= current_address + (number * size_of(data type))

Note:

32 bit

For 32 bit int variable, it will add 2 * number. 64 bit


For 64 bit int variable, it will add 4 * number. Example:

#include <stdio.h>
void main()
{
I nt 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+3; //adding 3 to pointer variable
printf("After adding 3: Address of p variable is %u \n",p);
}
Output

Address of p variable is 3214864300


After adding 3: Address of p variable is 3214864312

Subtraction (-):
Like pointer addition, we can subtract a value from the pointer variable. The formula of
subtracting value from pointer variable.
new_address= current_address - (number * size_of(data type))

Example:

#include <stdio.h>
void 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-3; //subtracting 3 from pointer variable
printf("After subtracting 3: Address of p variable is %u \n",p);
}
Output :
Address of p variable is 3214864300
After subtracting 3:
Address of p variable is 3214864288

Array of Pointers:
An array of pointers would be an array that holds memory locations. An array of pointers
is an indexed set of variables in which the variables are pointers (a reference to a location in
memory).

Syntax: data_type_name * variable name

Example: int *ptr[MAX];

Array alpha[] Pointer a

alpha[0] *a

alpha[1] *(a+1)

alpha[2] *(a+2)

alpha[3] *(a+3)

alpha[n] *(a+n)
Example1:
#include <stdio.h>
const int MAX = 3;
int main ()
{
int var[] = {10, 100, 200};
int i, *ptr[MAX];
for ( i = 0; i < MAX; i++)
{
ptr[i] = &var[i]; /* assign the address of integer. */
}
for ( i = 0; i < MAX; i++)
{
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
return 0;
}

Output:
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
Example2:
#include <stdio.h>
#include <conio.h>
main()
{
clrscr();
int *array[3];
int x = 10, y = 20, z = 30;
int i;
array[0] = &x;
array[1] = &y;
array[2] = &z;
for (i=0; i< 3; i++)
{
printf("The value of %d= %d ,address is %u\t \n", i, *(array[i]), array[i]);
}
getch();
return 0;
}
Output:
STRUCTURES, UNIONS, ENUMERATIONS AND TYPEDEF

Structure Definition

Structure is a user defined data type which hold or store heterogeneous/different types
data item or element in a single variable. It is a Combination of primitive and derived data type.
or
A structure is a collection of one or more data items of different data types, grouped
together under a single name.
Variables inside the structure are called members of structure. Each element of a structure
is called a member.
struct keyword is used to define/create a structure. struct define a new data type which is
a collection of different type of data.
Syntax
struct structure_name /tag name
{
data_type member1;
data_type member2;
data_type member n;
};

Note: Don't forget the semicolon }; in the ending line.

Example
struct employee
{
int id;
char name[50];
float salary;
};

Here, struct is th keyword,


employee is the tag name of structure;
id, name and salary are the members or fields of the structure.
Let's understand it by the diagram given below:
Syntax to create structure variable
struct tagname/structure_name variable;

Declaring structure variable


We can declare variable for the structure, so that we can access the member of structure
easily. There are two ways to declare structure variable:
1. By struct keyword within main() function/ Declaring Structure variables separately
2. By declaring variable at the time of defining structure/ Declaring Structure Variables with
Structure definition
1st way:
Let's see the example to declare 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.
struct employee e1, e2;
2nd way:

Let's see another way to declare variable at the time of defining structure.

struct employee
{
int id;
char name[50];
float salary;
}e1,e2;

Which approach is good


But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare
the structure variable many times.
If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in
main() function.
Structure Initialization
structure variable can also be initialized at compile time.
struct Patient
{
float height;
int weight;
int age;
};
struct Patient p1 = { 180.75 , 73, 23 }; //initialization
or
struct patient p1;
[Link] = 180.75; //initialization of each member separately
[Link] = 73;
[Link] = 23;

Accessing Structures/ Accessing members of structure


There are two ways to access structure members:
1. By . (member or dot operator)
2. By -> (structure pointer operator)

When the variable is normal type then go for struct to member operator. When the variable is
pointer type then go for pointer to member operator.

Any member of a structure can be accessed as:


structure_variable_name.member_name
Example
struct book
{
char name[20]; char author[20]; int pages;
};
struct book b1;
for accessing the structure members from the above example
[Link], [Link], [Link]:

Example
struct emp
{
int id;
char name[36]; int sal;
};

sizeof(struct emp) // --> 40 byte (2byte+36byte+2byte)

Example of Structure in C
#include<stdio.h>
#include<conio.h>
struct emp
{
int id;
char name[36];
float sal;
};
void main()
{
struct emp e; clrscr();
printf("Enter employee Id, Name, Salary: ");
scanf("%d",&[Link]);
scanf("%s",&[Link]);
scanf("%f",&[Link]);
printf("Id: %d",[Link]);
printf("\nName: %s",[Link]);
printf("\nSalary: %f",[Link]); getch();
}
Output
Enter employee Id, Name, Salary: 5 Spidy 45000
Id : 05
Name: Spidy
Salary: 45000.00

Difference Between Array and Structure

Structure is the collection of


1 Array is collection of homogeneous data.
heterogeneous data.
Structure elements are access using .
2 Array data are access using index.
operator.
3 Array allocates static memory. Structures allocate dynamic memory.
Array element access takes less time than Structure elements takes more time than
4
structures. Array.

Nested Structures
Structure can have another structure as a member. There are two ways to define nested
structure in c language:
1. By separate structure
2. By Embedded structure

1) Separate structure
We can create 2 structures, but dependent structure should be used inside the main structure as a
member. Let's see the code of nested structure.
struct Date
{
int dd;
int mm;
int yyyy;
};
struct Employee
{
int id;
char name[20];
struct Date doj;
}emp1;
2) Embedded structure

struct Employee
{
int id;
char name[20]; struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}emp1;

Accessing Nested Structure


We can access the member of nested structure by Outer_Structure.Nested_Structure.member as
given below:
[Link]
[Link]
[Link]

Arrays of Structures
Array of structures to store much information of different data types. Each element of the
array representing a structure variable. The array of structures is also known as collection of
structures.
Ex : if you want to handle more records within one structure, we need not specify the number of
structure variable. Simply we can use array of structure variable to store them in one structure
variable.
Example : struct employee emp[5];
Example of structure with array that stores information of 5 students and prints it.

#include<stdio.h>
#include<conio.h>
#include<string.h>
struct student{
int rollno;
char name[10];
};
void main()
{
int i;
struct student st[5];
clrscr();
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);
}
getch();
}

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

Self‐referential Structures

A structure consists of at least a pointer member pointing to the same structure is known
as a self-referential structure. A self referential structure is used to create data structures like
linked lists, stacks, etc. Following is an example of this kind of structure:
A self-referential structure is one of the data structures which refer to the pointer to
(points) to another structure of the same type. For example, a linked list is supposed to be a self-
referential data structure. The next node of a node is being pointed, which is of the same struct
type.
For example,
Syntax : struct tag_name
{
type member1; type membere2;
: :
: :
typeN memberN;
struct tag_name *name;
}
Where *name refers to the name of a pointer variable.
Ex:
struct emp
{
int code;
struct emp *name;
}

Unions
A union is a special data type available in C that allows to store different data types in the
same memory location.
Unions are conceptually similar to structures. The syntax of union is also similar to that of
structure. The only difference is in terms of storage. In structure each member has its own
storage location, whereas all members of union use a single shared memory location which is
equal to the size of its largest data member.
We can access only one member of union at a time. We can‟t access all member values at
the same time in union. But, structure can access all member values at the same time. This is
because, Union allocates one common storage space for all its members. Where as Structure
allocates storage space for all its members separately.
Syntax:
union union_name
{
data_type member1; data_type member2;
.
.
data_type memeberN;

};
Example:
union employee
{
int id;
char name[50];
float salary;
};

Example
#include <stdio.h>
#include <conio.h>
union item
{
int a; float b; char ch;
};
int main( )
{
union item it;it.a = 12;
it.b = 20.2;[Link]='z';
clrscr(); printf("%d\n",it.a);
printf("%f\n",it.b);
printf("%c\n",[Link]);getch();
return 0;
}
Output
-26426
20.1999
As you can see here, the values of a and b get corrupted and only variable c prints the
expected result. Because in union, the only member whose value is currently stored will have the
memory.

Difference between Structure and Union

Structure Union

For defining structure use


1 For defining union we use union keyword
struct keyword.

Structure occupies more


2 Union occupies less memory space than Structure.
memory space than union.

In Structure we can access


3 all members of structure at a In union we can access only one member of union at a time.
time.

Structure allocates separate Union allocates one common storage space for its all
4 storage space for its every members. Union find which member need more memory
members. than other member, then it allocate that much space

Bit‐Fields
Syntax
struct {
type [member_name] : width ;
};

The following table describes the variable elements of a bit field −

Elements Description

type An integer type that determines how a bit-field's value is interpreted.


The type may be int, signed int, or unsigned int.

member_name The name of the bit-field.

width The number of bits in the bit-field. The width must be less than or equal
to the bit width of the specified type.
The variables defined with a predefined width are called bit fields. A bit field can hold
more than a single bit; for example, if you need a variable to store a value from 0 to 7, then you
can define a bit field with a width of 3 bits as follows –
struct {
unsigned int age : 3;
} Age;

The above structure definition instructs the C compiler that the age variable is going to
use only 3 bits to store the value. If you try to use more than 3 bits, then it will not allow you to
do so. Let us try the following example –
#include <stdio.h>
#include <string.h>
struct {
unsigned int age : 3;
} Age;
int main( )
{
[Link] = 4;
printf( "Sizeof( Age ) : %d\n", sizeof(Age) );
printf( "[Link] : %d\n", [Link] ); [Link] = 7;
printf( "[Link] : %d\n", [Link] ); [Link] = 8;
printf( "[Link] : %d\n", [Link] ); return 0;
}
Output
Sizeof( Age ) : 4
[Link] : 4
[Link] : 7
[Link] : 0

Typedef:

The typedef is a keyword that allows the programmer to create a new data type name for
an existing data type. So, the purpose of typedef is to redefine the name of an existing variable
type.
Syntax
typedef datatype alias_name;

Example of typedef
#include<stdio.h>
#include<conio.h>
typedef int Intdata; // Intdata is alias name of int
void main()
{
int a=10;
Integerdata b=20;
typedef Intdata Integerdata; // Integerdata is again alias name of Intdata
Integerdata s;
clrscr();
s=a+b;
printf("\n Sum:= %d",s);
getch();
}
Output

Sum: 20

Advantages of typedef :
1) Provides a meaningful way of declaring the variable.
2) Increase the readability of the program.

#include<stdio.h>
#include<conio.h>
void main()
{
typedef int digits;
digits a,b,sum;
clrscr();
printf("Enter a and b values:");
scanf("%d%d",&a,&b);
sum=a+b;
printf("The sum is:%d",sum);
getch();
}

Note: By using typedef only we can create the alias name and it is under control of compiler.
Application of typedef

typedef can be used to give a name to user defined data type as well. Lets see its use with
structures.
typedef struct
{
type member1;
type member2;
type member3;
} type_name ;

Here type_name represents the stucture definition associated with it. Now this type_name can be
used to declare a variable of this stucture type.
type_name t1, t2 ;

Example of structure definition using typedef

#include<stdio.h>
#include<conio.h>
#include<string.h>
typedef struct employee
{
char name[50]; int salary;
} emp ;
void main( )
{
emp e1;
printf("\nEnter Employee record\n");
printf("\nEmployee name\t");
scanf("%s",[Link]);
printf("\nEnter Employee salary \t");
scanf("%d",&[Link]);
printf("\nstudent name is %s",[Link]);
printf("\nroll is %d",[Link]);
getch();
}

typedef and Pointers

typedef can be used to give an alias name to pointers also. Here we have a case in which
use of typedef is beneficial during pointer declaration.
In Pointers * binds to the right and not the left.
int* x, y ;
By this declaration statement, we are actually declaring x as a pointer of type int,
whereas y will be declared as a plain integer.
typedef int* IntPtr ;
IntPtr x, y, z;

But if we use typedef like in above example, we can declare any number of pointers in a
single statement.
NOTE : If you do not have any prior knowledge of pointers, do study Pointers first.
Enumerations
An enum is a keyword, it is an user defined data type. All properties of integer are
applied on Enumeration data type so size of the enumerator data type is 2 byte. It work like the
Integer.
It is used for creating an user defined data type of integer. Using enum we can create
sequence of integer constant value.
Syntax

enum tagname {value1, value2, value3,. };

 In above syntax enum is a keyword. It is a user defiend data type.

 In above syntax tagname is our own variable. tagname is any variable name.

 value1, value2, value3,. are create set of enum values.

It is start with 0 (zero) by default and value is incremented by 1 for the sequential
identifiers in the list. If constant one value is not initialized then by default sequence will be start
from zero and next to generated value should be previous constant value one.
Example of Enumeration in C
#include<stdio.h>
#include<conio.h>
enum ABC {x,y,z};
void main()
{
int a; clrscr();
a=x+y+z; //0+1+2
printf("Sum: %d",a);
getch();
}

Output

Sum: 3

You might also like