Download as pdf or txt
Download as pdf or txt
You are on page 1of 51

WEEK5

•Pointer to a Function

•Structures
• REF: . Kunal Pimparkhede - Computer Programming with C++ (2016, Cambridge University Press).
void Pointers
Void type pointers can point to a variable of any type. void pointers are universal
pointers so they have ability to point to data values of every type.

The code below creates two variables a and b of type int and float. It uses a void type
pointer p to access the value of each of these variables.

will make the void type pointer p to point to floating point variable a.
to copy the address stored in pointer p to pointer pint
We can access the values of variables a and b by applying indirection to pointers pint
and pflt as shown in the code.
Pointer to a Function

Pointers in C/C++ can also point to a function. To make a pointer point to a function,
type of the pointer must match with the prototype of the function.

Consider the given program, add() and sub() functions take two integer values as an
argument and return an integer as a result of execution. Since both of the function
have a same prototype, it is possible to create a single pointer which has an ability to
point to either of the functions.
Reference Variables (Only Available in C++ not in C)

A reference variable in C++ is another name given to a variable. we can give multiple
names to the same memory location by creating multiple references to the same location
Both statements will print a value 10 which is the
value stored in the memory location which has
two names a and sample.
Call by reference

When a function is called by passing the name of the actual parameters as argument
instead of passing the values, the function call is then defined as a ‘call by reference’
Call by reference Execution of the statement p++
Creating Lvalue’d function using reference variables
(Possible only in C++ and not in C)

Lvalue’d function is a function which can appear as an Lvalue in the expression.

Reference variables and pointers both can be used to create Lvalue’d function.

In this section, we will implement an Lvalue’d function using reference variables


Consider, the following code which creates a global variable a initialized with a value
10 and function f1() which increments the value of a and returns to function main().

The first statement in main(), f1()=20; attempts to call a function f1() as a Lvalue
(The function call is placed on the left-hand side of assignment operator)
• As per the function definition of f1() it increments the value of a and
returns the resultant value. So, the function f1() returns 11.

• the function returns the value of a and not the memory location
where a is stored.

• Hence the following statement, f1()=20 is decayed as: 11=20;

• This statement does not make any sense because 11 is a constant


whose value cannot be changed.

• Hence, the program crashes with a following error: Lvalue required in


the statement f1()=20;
This means that the function must return the reference or address of the memory
location rather than returning the value stored inside the location.
• This time the statement f1()=20; works perfectly fine because the function
f1() decays to a reference variable which returns the memory location of
variable a.

• Although a stores 11 at a point where f1() completes its execution, the


statement f1()=20; will modify the value of variable a to 20.

• Hence the statement, printf("Value of a is %d",a); in main() function will print


the value of a as 20 on the computer screen.
NOTES
• When program throws an error as Lvalue required, it means that there is an illegal
expression used on the left-hand side of assignment operator in at least one of the
statements.
• The following statement will not work k+1=50; This is because k+1 is an expression
which returns a constant value. Let’s say, the value of k is 289, then k+1 will return a
constant value 290. As 290 is a Rvalue, the statement gets decayed into 290=50;
which does not make any sense.

• Hence the program crashes throwing Lvalue required. To make this logic work, you
must rewrite the statement as k=50-1; This will work perfectly fine because left-
hand side of assignment is a simple variable. Hence the statement will set the value
of k as 49.
Structures

• Structure is a template used to create a user-defined data type.


• This means that, as we create the variables of built-in data types, such
as int, float, and double, we can now, also create the variables of user-
defined data types,

• Structure is a way to combine the logically related data elements into a


single unit.

• Each of the data elements defined inside the structure, are called the
members of a structure.

• The members defined inside the structure can be of a same or different


data types.
Creating Structures

Syntax of a structure
• Once the structure is defined, we can now create variables of type structure
similar to how we create variables of any of the basic data types such as int,
float, and char.

• The variables which are of type defined by the structure are called as
objects of the structure. The following is the syntax to create objects of a
structure:
Object memory for o1 and o2
The total memory required by any object will be the addition of the amount of
memory required by each of its members.

The set of ‘values’ of the member variables of a particular object is called


as a ‘state’ of that object.
Assume that we need to store information about three books in the computer
memory. Since this is a common requirement that, we need to store the members id,
title, author, and price for each of the books, we can define a template for every
book using a structure as shown below:
• The variable b1 contains members id, title, author and price in its memory;

• So making it possible to store complete information about a particular book in


b1.

• We can similarly, create multiple variables of type Book and each variable will
contain all the members of the structure
The variable b1 is now called as an ‘object’ of a structure Book. The object memory
of b1 will contain members id, title, author and price

Object memory of b1
In C++, you can also create an object b1 by omitting keyword struct as shown in
the statement below:

Book b1;
As we need to store data about three books, we create two more variables of
type Book by using the following statement:

Structure of objects b2 and b3


Each of the objects of the structure Book in computer memory represents one book
in real world
We can access the attributes id, title, author, and price of each of the Book objects
by using a membership operator ‘.’ (DOT) using the following notation
Initialization of member variable title for each of the objects
Storage of values for member title(In actuality title and author are pointers)
we initialize all the members of the object in a single statement,

Initialization can only be applied at the time of creation of the object and not later than
that,
Can we initialize the members of the structure within the structure definition?

NO! This is because the memory for members is not allocated until an object of a
structure is created
Program to store the information about books in the computer memory: An
example
Create a program that stores the data about three books in a computer memory
and prints the information about each of the Book objects in a tabular format.

Let us store the following information about each book in the


computer memory:

1. Identification number of the book in a library


2. Title of the book
3. Author of the book
4. Price of the book
We can create Book as a user-defined data type by defining a structure

Notes In this case we have created members title and author as arrays rather
than pointers. This is because we intend to accept this information as input from
the user rather than directly initializing them as string constants
Memory allocation of a structure object with arrays embedded within the object space
As we need to store the information about three books in computer memory, the
following code creates three objects of a Book taking the details of each Book object as
input from the user and printing them back on screen.
State of objects b1, b2 and b3
SHORTHAND NOTATION TO CREATE OBJECTS
It is possible to create objects of a structure by specifying a comma separated list
of object names along with the structure definition.

Since structure Book is defined globally the objects b1, b2 and b3 will also be
created as global objects. On the other hand, if b1, b2 and b3 are created in main()
using the statement

the objects will be local to main() function even if the structure Book is defined
globally
Syntax for creating objects of a structure using shorthand notation
Array of Structure Objects
It is possible to create an array such that each element of the array is an object of
structure. Let us consider the structure Book; We can create an array of Book
objects named as b by using

The following statement will create an array b to store information about


three books in the computer memory:

Each element of the array b is an object of Book, because the data type of the array
b is defined as Book.
Array of objects b
For example, the following statement will accept the members (id, title, author, and
price) of object b[0] as input from the user:

Since we have only taken the members of b[0] as input, the state of array b assuming
input data as (id=1, title="C++", author="Kunal", price=900)
Initialization of objects
for(i=0;i<=2;i++)
{
scanf("%d%s%s%f",&b[i].id,b[i].title,b[i].author,&b[i].price);
}
In general, we can access a member of ith Book object in b by using the following
statement:

Following for loop will print the details of each of the Book objects on the computer
screen:

The output of the given for loop will be


#include<stdio.h>
struct Book
{
int id;
The following is char title[100];
char author[100];
the full source float price;
code which };
void main()
creates an array {
of type Book of int i;
/*Create an array of books with size 3*/
size 3, accepts the struct Book b[3];
details about each printf("Enter the id,title,author and price of 3 books\n");
book as input for(i=0;i<=2;i++)
{
from the user and scanf("%d%s%s%f",&b[i].id,b[i].title,b[i].author,&b[i].price);
prints them. }
printf("The Book details are\n");
for(i=0;i<=2;i++)
{
printf("%d\t%s\t%s\t%f\n", b[i].id, b[i].title, b[i].author, b[i].
price);
}
}
INITIALIZATION OF ARRAY OF OBJECTS

Array of objects can be initialized directly at the time of creation as follows:


Note that such an initialization can only be applied at the time of creation of an
array and not later then that.

For example, the following code will not work because it first creates an array b
and then initializes all its objects in the second statement.
If you need to initialize members of an array after its creation, you have to initialize
them one at a time as shown below

• Similarly, members of object b[1] and


b[2] can be initialized.

• Note that the arrays title and author are


initialized one character at a time
because string initialization can be
applied to the array only at the time of
creation and no later than that

You might also like