KEMBAR78
Unit 3 | PDF | Pointer (Computer Programming) | Computer Programming
0% found this document useful (0 votes)
10 views11 pages

Unit 3

Uploaded by

priyavenkat171
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)
10 views11 pages

Unit 3

Uploaded by

priyavenkat171
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/ 11

UNIT - III:

 It is also known as indirection pointer used to dereference a


Pointers: Introduction – Pointer Expressions – Chain of Pointers –Pointers pointer.
and Arrays – Array of Pointers – Pointers as function arguments – Functions
returning Pointers – Pointers to Functions – Function pointer – Structures - Syntax: data_type * pointer_name
declaration, initialization, Array of Structures – Pointer to structures, Structures and Example : int *a;//pointer to int
functions – Typedef, Enumerated data types, Unions.
char *c;//pointer to char
POINTER Example Program:
 A Pointer is a variable which holds the address of another variable
#include<stdio.h>
of same data type.
void main( )
Concept of Pointers
{
 A variable is declared in a program, system allocates a location i.e
int number=50;
an address to that variable in the memory, to hold the assigned
int *p;
value.
p=&number; //stores the address of number variable
 The memory location has its own address number.
printf("Address of p variable is %x \n",p); // p contains the address
Example :
of the number
Let us assume that system has allocated memory location 80F
therefore printing p
for a variable a.
gives the address of number.
int a = 10;
printf("Value of p variable is %d \n",*p); // get the value stored at
the address contained by p.
}
Output

DECLARING A POINTER Address of number variable is fff4

 The pointer can be declared using * (asterisk symbol). Address of p variable is fff4
Value of p variable is 50
INITIALIZATIONS OF POINTER VARIABLE int num = 100;

 Address operator (&) is used to initialize a pointer variable. int *ptr; //pointer variable
//pointer initialization
Syntax: data_type * pointer_variable = & variable;
ptr = &num;
Example:
//printing the value
// Declaration of integer variable printf("value of num = %d\n", *ptr);

int var=10; }
Uses of Pointers
// Initialization of pointer variable
 Pointers are used to access memory and manipulate the address.
int *pointer=&var;
 Pointer provides power and flexibility to the language.
ACCESSING A VARIABLE THROUGH ITS POINTERS Advantages of Pointers
 Access the value of another variable using the pointer variable. 1. Pointers are useful for accessing memory locations.
Steps: 2. Pointers provide an efficient way for accessing the elements of an
 Declare a normal variable, assign the value. array structure.
 Declare a pointer variable with the same type as the normal 3. Pointers are used for dynamic memory allocation as well as
variable. deallocation.
 Initialize the pointer variable with the address of normal variable. 4. Pointers are used to form complex data structures such as linked
 Access the value of the variable by using asterisk (*) - it is known as list, graph, tree, etc.
dereference operator (indirection operators). Disadvantages of Pointer
Example Program: 1. Pointers are a little complex to understand.
#include <stdio.h> 2. Pointers can lead to various errors such as segmentation faults or
void main() can access a memory location which is not required at all.
{ 3. If an incorrect value is provided to a pointer, it may cause memory
//normal variable corruption.
4. Pointers are also responsible for memory leakage. // Program showing pointer expressions during Arithmetic Operations
5. Pointers are comparatively slower than that of the variables. #include <stdio.h>
6. Programmers find it very difficult to work with the pointers; void main()
therefore it is programmer's responsibility to manipulate a pointer {
carefully. // Integer variables
POINTER EXPRESSION int a = 20, b = 10;
 Pointers are valid operands in arithmetic expressions, assignment // Variables for storing arithmetic // operations solution
expressions and comparison expressions. int add, sub;
// Pointer variables for variables a and b
int *ptr_a, *ptr_b;
// Initialization of pointers
ptr_a = &a;
ptr_b = &b;
// Performing arithmetic Operations on pointers
add = *ptr_a + *ptr_b;
sub = *ptr_a - *ptr_b;
 To perform arithmetic operations to pointer variables using // Printing values
arithmetic operators, we can add an integer or subtract an integer printf("Addition = %d\n", add);
using a pointer pointing to that integer variable. printf("Subtraction = %d\n", sub);
Examples: }
*ptr1 + *ptr2 Output:
*ptr1 * *ptr2 Addition = 30
*ptr1 + *ptr2 - *ptr3 Subtraction = 10
Example Program:
CHAIN OF POINTERS Pointers and Arrays

 A pointer is used to point to a memory location of a variable.  Variable declared as an array of some type acts as a pointer to that
 A pointer stores the address of a variable. type. When used by itself, it points to the first element of the array.
 Similarly, a chain of pointers is when there are multiple levels of  A pointer can be indexed like an array name.
pointers.
 The level of the pointer depends on how many asterisks the pointer
variable is preceded with at the time of declaration.

Syntax:

// level-1 pointer declaration

datatype *pointer;

// level-2 pointer declaration

datatype **pointer;

// level-3 pointer declaration

datatype ***pointer; Example:


#include <stdio.h>
void main( )
{
int i, x[6], sum = 0;
printf("Enter 6 numbers: ");
for(i = 0; i < 6; ++i)
{
scanf("%d", x+i);
sum = sum + *(x+i);
} arr[0] = &a;
printf("Sum = %d", sum); arr[1] = &b;
} arr[2] = &c;
Output printf("Address of a = %p\n",arr[0]);
Sum = 150 printf("Address of b = %p\n",arr[1]);
ARRAY OF POINTER printf("Address of c = %p\n",arr[2]);
 “Array of pointers” is an array of the pointer variables. for(i = 0; i < size; i++)
 It is also known as pointer arrays. printf("value stored at arr[%d] = %d\n",i,*arr[i]);
Syntax: }

data type (*var name)[size of array]; POINTERS AS FUNCTION ARGUMENT


 Pointer as a function parameter is used to hold addresses of
Example
arguments passed during function call.
 Create an array of 5 pointers
 This is also known as call by reference.
int *arr[5];
 When a function is called by reference any change made to the
Where
reference variable will affect the original variable.
arr[0] will hold one integer variable address,
Example:
arr[1] will hold another integer variable address and so on.
#include <stdio.h>
Example Program
void swap(int *a, int *b);
#include<stdio.h>
void main()
#define size 3
{
void main()
int m = 10, n = 20;
{
printf("m = %d\n", m);
int *arr[size];
printf("n = %d\n\n", n);
int a = 10, b = 20, c = 30, i;
swap(&m, &n); //passing address of m and n to the swap function
printf("After Swapping:\n\n"); void hello()
printf("m = %d\n", m); {
printf("n = %d", n); printf("Hello\n");
} }
/* pointer 'a' and 'b' holds and points to the address of 'm' and 'n' */ void main()
void swap(int *a, int *b) {
{ //function name itself holds the memory address of a function
int temp; printf("Address of function hello = %p\n",hello);
temp = *a; }
*a = *b; Output
*b = temp; Address of function hello = 0x4004f0
} STRUCTURES
Output:  A structure is a key word that creates user defined data type in C
m = 10  A structure creates a data type that can be used to group items of
n = 20 possibly different types into a single type.
 The structure allows initializing multiple variable members at once.
After Swapping:
 structure is another user defined data type available in C
m = 20
How to create a structure?
n = 10
 ‘struct’ keyword is used to create a structure.
POINTER TO FUNCTION
Syntax:
 Like the pointer to normal variables, we can also use pointers to
point the functions. struct structureName
Example: {
#include<stdio.h>
dataType member1;
dataType member2; float salary;

... };
void main()
};
{
Example:
struct Person person1, person2, p[20];
}
How to Initialize Structure Members?
 Structure members cannot be initialized like other variables inside
the structure definition.
 Because when a structure is defined, no memory is allocated to the
structure’s data members at this point. Memory is only allocated
when a structure variable is declared.
Example:
struct rectangle
struct rectangle
{
{
Create struct Variables // structure definition
// structure definition
 When a struct type is declared, no storage or memory is allocated. int length;
int length = 10; // COMPILER ERROR:
 To allocate memory of a given structure type and work with it, we int breadth;
cannot
};
need to create variables. initialize members here.
void main()
Example int breadth = 6; // COMPILER ERROR:
{
struct Person cannot
struct rectangle my_rect; // structure
{ initialize members here.
variables;
char name[50]; };
my_rect.length = 10;
int citNo; my_rect.breadth = 6;

}
Access Members of a Structure printf("Roll No.: %d\n", student1.rollno);
 There are two types of operators used for accessing members of a printf("College: %s", student1.college);
structure. }
. Member operator Output
-> Structure pointer operator Name : Hariharasudhan.S
Example Program Roll No : 2001
#include <stdio.h> College : SRM Trichy Arts and Science College
#include <string.h> Array of Structures
// create struct with person1 variable  An array of structures acts similar to a normal array.
struct student  The name of the structure followed by the dot operator (.) and the
{ name of the array has to be mentioned to access an array element.
char name[50];  To store the details of 100 students name, class, and roll number in
int rollno; your database, we use array of structures.
char college[50]; Example:
#include <stdio.h>
} student1;
// structure definition
void main() struct Student
{
{
// data members
// assign value to name of person1 char name[10];
int marks;
strcpy(student1.name, "Hariharasudhan.S");
};
// assign values to other person1 variables // declare an array of the structure Student.
struct Student stu[3];
person1.rollno = 2001;
int i, j;
person1. college = “SRM Trichy Arts and Science College”; // function to read the values from the user and print them.
void print()
// print struct variables
{
printf("Name: %s\n", student1.name); // read input from the user.
for (i = 0; i < 3; i++) Student Name : S. Hariharasudhan
{ Enter marks : 99
printf("\nEnter the record of Student %d\n", i + 1); Student Name : M.Prabhu
printf("\nStudent name: "); Enter marks : 98
scanf("%s", stu[i].name); Keyword typedef
printf("Enter Marks: ");
 Use the typedef keyword to create an alias name for data types.
scanf("%d", &stu[i].marks);
}  It is commonly used with structures to simplify the syntax of
// print the details of each student.
declaring variables.
printf("\nDisplaying Student record\n"); Example 1: (without using typedef)
for (i = 0; i < 3; i++)
struct Distance
{
printf("\nStudent name is %s", stu[i].name); {
printf("\nMarks is %d", stu[i].marks);
int feet;
}
} float inch;
void main()
};
{
// function call void main()
print();
{
}
Output: struct Distance d1, d2;
Enter the record of Student 1
}
Student Name : S. MONICA
Enter marks : 98 Example 2 : (Using typedef keyword)
Enter the record of Student 2
typedef struct Distance
Student Name : S. Hariharasudhan
Enter marks : 99 {
Enter the record of Student 3
int feet;
Student Name : M.Prabhu
Enter marks : 98 float inch;
Displaying Student record
} distances;
Student Name : S. MONICA
Enter marks : 98 void main()
{ void printBook( struct Books *book );
void main( )
distances d1, d2;
{
} struct Books Book1; // Declare Book1 of type Book
strcpy( Book1.title, "C Programming"); // book 1
POINTERS AND STRUCTURES
specification
 Define pointers to structures in the same way as we define strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
pointer to any other variable.
Book1.book_id = 6495407; // print Book1 info by
struct Books *struct_pointer; passing address of Book1
}
 Now, we can store the address of a structure variable in the
void printBook( struct Books *book )
above defined pointer variable. {
printf( "Book title : %s\n", book->title);
 To find the address of a structure variable, place the ‘&’;
printf( "Book author : %s\n", book->author);
operator before the structure’s name as printf( "Book subject : %s\n", book->subject);
printf( "Book book_id : %d\n", book->book_id);
follows
}
struct_pointer = &Book1; Output:
Book title : C Programming Book
 To access the members of a structure using a
Author : Nuha Ali
pointer to that structure, we must use the → operator as Book subject : C Programming Tutorial
Book book_id : 6495407
follows −
UNION
struct_pointer->title;
 A union is a special data type available in C
Example Program
 It allows storing different data types in the same memory location.
#include <stdio.h>
#include <string.h>  Unions provide an efficient way of using the same memory location
struct Books
for multiple-purpose.
{
char title[50]; Defining a Union
char author[50];
 Union keyword is used to define union structure.
char subject[100];
int book_id;  The union statement defines a new data type with more than one
};
member for our program. printf("\n b = %d", var.b);
Syntax: }
union [union tag] Differences between Structure and Union
{ Structure Union
member definition;
1. use a struct keyword to define 1. use a union keyword to
member definition; a structure. define a union.
... 2. Every member within structure 2. A memory location is shared
is assigned a unique memory by all the data members.
member definition; location.
} [one or more union variables]; 3. Changing the value of one data 3. Changing the value of one
member will not affect other data member will change the
Accessing Union Members data members in structure value of other data members
 To access any member of a union, use the member access operator in union.
4. It enables you to initialize 4. It enables you to initialize
(.). several members at once. only the first member of
 The member access operator is coded as a period between the union.
5. It is mainly used for storing 5. It is mainly used for storing
union variable name and the union member that we wish to access. various data types. one of the many data types
Example: that are available.
6. It supports flexible array. 6. It does not support a flexible
union abc array.
{ 7. You can retrieve any member 7. You can access one member
at a time. at a time in the union.
int a; 8. It occupies space for each and 8. It occupies space for a
char b; every member written in inner member having the highest
parameters. size written in inner
}var; parameters.
void main() 9. The total size of the structure is 9. The total size of the union is
the sum of the size of every the size of the largest data
{ data member. member.
var.a = 66;
printf("\n a = %d", var.a);

You might also like