PPL Notes BCAC201
PPL Notes BCAC201
Topic:Pointer
1.What is a Pointer in C?
Ans:Assume that there is another variable ptr which holds the address of x means :
int *ptr;
ptr = & x;
this statement assigns the address of x to the variable ptr and
ptr is said to ‘point to’ x .
Ptr is called as pointer .It does not store simple values .instead of this it store reference or
address to another variable . A pointer holds the address of the very first byte of the
memory location where it is pointing to. the address of the first byte is also known as base
address.
Def
ptr is a pointer variable which contains the address of some other variable ( of type integer
in this case) . Then obviously a pointer variable is not the same type as integer variable .
then how they are declared like
where ptr is not an integer variable but ptr can hold the address of the integer variable i.e.
it is a ‘pointer to an integer variable’ ,but the declaration of pointer variable does not
make them point to any location .
int i=57
57
This is the initialization of the pointer variable. since the pointer can point to any
portion of the memory ,it is a good programming practice to initialize the pointer .
Void Pointer
Every pointer points to a specific data type except ‘ a pointer to void ‘ which can point to
any data type form double to characters but it cannot be directly dereferenced .It has a
great facility of pointing to any data type. It can only be dereferenced by casting the
address in the void pointer to a concrete data type before dereferencing it . This
conversion of pointer to some other valid data type is achieved by using the concept of
typecasting .It is generally use to pass generic arguments to functions.
All these statements are valid , as void pointer can point to objects of any data type.
Direct dereferencing of void pointer is not permitted. The void pointer must first be
explicitly cast to another pointer type before it is dereferenced. Also it is not possible to do
pointer arithmetic on a void pointer.
Pointer arithmetic
Hope you must have understood the declaration and initialization of variables . Now we
will see how we can manipulate the pointer variables. Pointer arithmetic operations are
different from normal arithmetic operations.
These operations may be allowed to perform on Pointers:
Add or subtract integers to/from a pointer. The result is a pointer.
Subtract two pointers to the same type. The result is an int.
Multiplying, adding two pointers, etc. don't make sense.
char *mychar;
short *myshort;
long *mylong;
and that we know that they point to memory locations 1000, 2000 and 3000 respectively ,
So we Write
mychar++; or mychar=mychar+ 1
myshort++; or myshort = mshort + 1
mylong++; or mylong = mylong +1
incrementing a pointer by 1 makes it point to memory location given by the formula new
address = old address+ scaling factor.
Decrementing a pointer by 1 makes it point to the memory location given by the formula :
The Assignment operation (=) between two pointers make them point to the same
thing
Topic:Function
1. What is C function?
A large C program is divided into basic building blocks called C function. C function contains set of
instructions enclosed by “{ }” which performs specific operation in a C program. Actually,
Collection of these functions creates a C program.
2. Uses of C functions:
• C functions are used to avoid rewriting same logic/code again and again in a program.
• There is no limit in calling C functions to make use of same functionality wherever required.
• We can call functions any number of times in a program and from any place in a program.
• A large C program can easily be tracked when it is divided into functions.
• The core concept of C functions are, re-usability, dividing a big task into small pieces to
achieve the functionality and to improve understandability of very large C programs.
#include<stdio.h>
// function prototype, also called function declaration
float square ( float x );
// main function, program starts from here
int main( )
{
float m, n ;
printf ( "\nEnter some number for finding square \n");
scanf ( "%f", &m ) ;
// function call
n = square ( m ) ;
printf ( "\nSquare of the given number %f is %f",m,n );
}
1. Call by value:
• In call by value method, the value of the variable is passed to the function as parameter.
• The value of the actual parameter can not be modified by formal parameter.
• Different Memory is allocated for both actual and formal parameters. Because, value of
actual parameter is copied to formal parameter.
Note:
• Actual parameter – This is the argument which is used in function call.
• Formal parameter – This is the argument which is used in function definition
Example program for C function (using call by value):
• In this program, the values of the variables “m” and “n” are passed to the function “swap”.
• These values are copied to formal parameters “a” and “b” in swap function and used.
#include<stdio.h>
// function prototype, also called function declaration
void swap(int a, int b);
int main()
{
int m = 22, n = 44;
// calling swap function by value
printf(" values before swap m = %d \nand n = %d", m, n);
swap(m, n);
}
Call by reference:
• In call by reference method, the address of the variable is passed to the function as
parameter.
• The value of the actual parameter can be modified by formal parameter.
• Same memory is used for both actual and formal parameters since only address is used by
both parameters.
#include<stdio.h>
// function prototype, also called function declaration
void swap(int *a, int *b);
int main()
{
int m = 22, n = 44;
//calling swap function by reference
printf("values before swap m = %d \n and n = %d",m,n);
swap(&m, &n);
}
function definition:
void function( int a )
{
statements;
}
function declaration:
void function();
function declaration:
int function ( );
Note:
• If the return data type of a function is “void”, then, it can’t return any values to the calling
function.
• If the return data type of the function is other than void such as “int, float, double etc”, then,
it can return values to the calling function.
Recursion:
Recursion is the process of repeating items in a self-similar way. In programming languages, if a
program allows you to call a function inside the same function, then it is called a recursive call of
the function.
void recursion() {
recursion(); /* function calls itself */
}
int main() {
recursion();
}
The C programming language supports recursion, i.e., a function to call itself. But while using
recursion, programmers need to be careful to define an exit condition from the function, otherwise it
will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as calculating the
factorial of a number, generating Fibonacci series, etc.
Number Factorial
The following example calculates the factorial of a given number using a recursive function −
#include <stdio.h>
if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}
int main() {
int i = 15;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
When the above code is compiled and executed, it produces the following result −
Factorial of 15 is 2004310016
Fibonacci Series
The following example generates the Fibonacci series for a given number using a recursive function
−
#include <stdio.h>
int fibonacci(int i) {
if(i == 0) {
return 0;
}
if(i == 1) {
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}
int main() {
int i;
return 0;
}
Arrays allow to define type of variables that can hold several data items of the same kind. Similarly
structure is another user defined data type available in C that allows to combine data items of
different kinds.
Structures are used to represent a record. Suppose you want to keep track of your books in a library.
You might want to track the following attributes about each book −
• Title
• Author
• Subject
• Book ID
Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines a new data
type, with more than one member. The format of the struct statement is as follows −
struct [structure tag] {
member definition;
member definition;
...
member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal variable definition, such as
int i; or float f; or any other valid variable definition. At the end of the structure's definition, before
the final semicolon, you can specify one or more structure variables but it is optional. Here is the
way you would declare the Book structure −
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( ) {
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "PQR");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
return 0;
}
C - Unions
A union is a special data type available in C that allows to store different data types in the same
memory location. You can define a union with many members, but only one member can contain a
value at any given time. Unions provide an efficient way of using the same memory location for
multiple-purpose.
Defining a Union
To define a union, you must use the union statement in the same way as you did while defining a
structure. The union statement defines a new data type with more than one member for your
program. The format of the union statement is as follows −
union [union tag] {
member definition;
member definition;
...
member definition;
} [one or more union variables];
The union tag is optional and each member definition is a normal variable definition, such as int i;
or float f; or any other valid variable definition. At the end of the union's definition, before the final
semicolon, you can specify one or more union variables but it is optional. Here is the way you
would define a union type named Data having three members i, f, and str −
union Data {
int i;
float f;
char str[20];
} data;
Now, a variable of Data type can store an integer, a floating-point number, or a string of characters.
It means a single variable, i.e., same memory location, can be used to store multiple types of data.
You can use any built-in or user defined data types inside a union based on your requirement.
The memory occupied by a union will be large enough to hold the largest member of the union. For
example, in the above example, Data type will occupy 20 bytes of memory space because this is the
maximum space which can be occupied by a character string. The following example displays the
total memory size occupied by the above union −
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
return 0;
}
When the above code is compiled and executed, it produces the following result −
Memory size occupied by data : 20
union Data {
int i;
float f;
char str[20];
};
int main( ) {
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
return 0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Here, we can see that the values of i and f members of union got corrupted because the final value
assigned to the variable has occupied the memory location and this is the reason that the value of str
member is getting printed very well.
Now let's look into the same example once again where we will use one variable at a time which is
the main purpose of having unions −
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
return 0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 10
data.f : 220.500000
data.str : C Programming
Here, all the members are getting printed very well because one member is being used at a time.
C – Dynamic Memory Management
In C, the exact size of array is unknown until compile time, i.e., the time when a compiler compiles
your code into a computer understandable language. So, sometimes the size of the array can be
insufficient or more than required.
Dynamic memory allocation allows your program to obtain more memory space while running, or
to release it if it's not required.
In simple terms, Dynamic memory allocation allows you to manually handle memory space for
your program.
Although, C language inherently does not have any technique to allocate memory dynamically,
there are 4 library functions under "stdlib.h" for dynamic memory allocation.
C malloc()
The name malloc stands for "memory allocation".
The function malloc() reserves a block of memory of specified size and return a pointer of type
void which can be casted into pointer of any form.
Syntax of malloc()
ptr = (cast-type*) malloc(byte-size)
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory
with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.
ptr = (int*) malloc(100 * sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and
the pointer points to the address of first byte of memory.
C calloc()
The name calloc stands for "contiguous allocation".
The only difference between malloc() and calloc() is that, malloc() allocates single block of
memory whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes
to zero.
Syntax of calloc()
ptr = (cast-type*)calloc(n, element-size);
This statement will allocate contiguous space in memory for an array of n elements. For example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each of size of
float, i.e, 4 bytes.
C free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on its own.
You must explicitly use free() to release the space.
syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
int main()
{
int num, i, *ptr, sum = 0;
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
C realloc()
If the previously allocated memory is insufficient or more than required, you can change the
previously allocated memory size using realloc().
Syntax of realloc()
ptr = realloc(ptr, newsize);
Here, ptr is reallocated with size of newsize.
int main()
{
int *ptr, i , n1, n2;
printf("Enter size of array: ");
scanf("%d", &n1);