0% found this document useful (0 votes)
11 views18 pages

PPL Notes BCAC201

Pointer is a variable that stores the address of another variable. A pointer variable contains the memory address of the variable it points to. Pointers allow access and modification of the value of the variable being pointed to. There are different types of pointers like void pointers that can point to any data type. Pointer arithmetic allows adding or subtracting integers from pointers to manipulate the memory addresses. Functions allow dividing programs into smaller and reusable blocks of code. Functions can be called with or without arguments and may return a value. There are different ways functions can be called like call by value and call by reference. Call by value passes the value of an argument whereas call by reference passes the address, allowing the original variable to be modified.

Uploaded by

kiway68577
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)
11 views18 pages

PPL Notes BCAC201

Pointer is a variable that stores the address of another variable. A pointer variable contains the memory address of the variable it points to. Pointers allow access and modification of the value of the variable being pointed to. There are different types of pointers like void pointers that can point to any data type. Pointer arithmetic allows adding or subtracting integers from pointers to manipulate the memory addresses. Functions allow dividing programs into smaller and reusable blocks of code. Functions can be called with or without arguments and may return a value. There are different ways functions can be called like call by value and call by reference. Call by value passes the value of an argument whereas call by reference passes the address, allowing the original variable to be modified.

Uploaded by

kiway68577
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/ 18

Principle of Programming Langue Notes and question answer-1

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

A pointer is a variable which contains the address of another variable.

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

assigning address of i to ptr , ptr = & i; will result in

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
type­casting .It is generally use to pass generic arguments to functions.

void * vptr; //declaration of void pointer


int i;
float f;
double d;
the statements
vptr = &i //making the pointer vptr point to integer type of variable
vptr = &f //making the pointer vptr point to float type of variable
vptr = &d //making the pointer vptr point to double type of variable

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.

Example : 7.4 showing pointer arithmetic

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 :

newaddress = old address – scaling factor


 Both addition and subtraction operation depend upon the size of data type pointer variable
points to.
 Both the increase (++) and decrease (­­) operators have greater operator precedence than
the dereference operator (*),

 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.

3. C function declaration, function call and function definition:


There are 3 aspects in each C function. They are,
• Function declaration or prototype – This informs compiler about the function name,
function parameters and return value’s data type.
• Function call – This calls the actual function
• Function definition – This contains all the statements to be executed.

C functions aspects syntax


Return_type function_name (arguments list)
function definition
{ Body of function; }
function call function_name (arguments list);
function declaration return_type function_name (argument list);
Simple example program for C function:
• As you know, functions should be declared and defined before calling in a C program.
• In the below program, function “square” is called from main function.
• The value of “m” is passed as argument to the function “square”. This value is multiplied by
itself in this function and multiplied value “p” is returned to main function from function
“square”.

#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 );
}

float square ( float x )// function definition


{
float p ;
p=x*x;
return ( p ) ;
}

How to call C functions in a program?


There are two ways that a C function can be called from a program. They are,
1. Call by value
2. Call by reference

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);
}

void swap(int a, int b)


{
int tmp;
tmp = a;
a = b;
b = tmp;
printf(" \nvalues after swap m = %d\n and n = %d", a, b);
}

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.

Example program for C function (using call by reference):


• In this program, the address of the variables “m” and “n” are passed to the function “swap”.
• These values are not copied to formal parameters “a” and “b” in swap function.
• Because, they are just holding the address of those variables.
• This address is used to access and change the values of the variables.

#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);
}

void swap(int *a, int *b)


{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
printf("\n values after swap a = %d \nand b = %d", *a, *b);
}

C – Argument, return value(4 cases)


All C functions can be called either with arguments or without arguments in a C program. These
functions may or may not return values to the calling function. Now, we will see simple example C
programs for each one of the below.
1. C function with arguments (parameters) and with return value.
2. C function with arguments (parameters) and without return value.
3. C function without arguments (parameters) and without return value.
4. C function without arguments (parameters) and with return value.

C functions aspects syntax


function declaration:
int function ( int );

function call: function ( a );

1. With arguments and with function definition:


return values int function( int a )
{
statements;
return a;
}

2. With arguments and without function declaration:


return values void function ( int );

function call: function( a );

function definition:
void function( int a )
{
statements;
}

function declaration:
void function();

function call: function();


3. Without arguments and without
function definition:
return values
void function()
{
statements;
}

function declaration:
int function ( );

function call: function ( );

4. Without arguments and with function definition:


return values int function( )
{
statements;
return a;
}

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>

int factorial(unsigned int i) {

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;

for (i = 0; i < 10; i++) {


printf("%d\t\n", fibonacci(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;

Accessing Structure Members


To access any member of a structure, we use the member access operator (.). The member access
operator is coded as a period between the structure variable name and the structure member that we
wish to access. You would use the keyword struct to define variables of structure type. The
following example shows how to use a structure in a program −
#include <stdio.h>
#include <string.h>

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};

int main( ) {

struct Books Book1; /* Declare Book1 of type Book */


struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "ABC");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;

/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "PQR");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;

/* print Book1 info */


printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);

/* print Book2 info */


printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n", Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id);

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( ) {

union Data data;

printf( "Memory size occupied by data : %d\n", sizeof(data));

return 0;
}

When the above code is compiled and executed, it produces the following result −
Memory size occupied by data : 20

Accessing Union Members


To access any member of a union, we use the member access operator (.). The member access
operator is coded as a period between the union variable name and the union member that we wish
to access. You would use the keyword union to define variables of union type. The following
example shows how to use unions in a program −
#include <stdio.h>
#include <string.h>

union Data {
int i;
float f;
char str[20];
};

int main( ) {

union Data data;

data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");

printf( "data.i : %d\n", data.i);


printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);

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( ) {

union Data data;

data.i = 10;
printf( "data.i : %d\n", data.i);

data.f = 220.5;
printf( "data.f : %f\n", data.f);

strcpy( data.str, "C Programming");


printf( "data.str : %s\n", data.str);

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.

Function Use of Function


malloc() Allocates requested size of bytes and returns a pointer first byte of allocated space
Allocates space for an array elements, initializes to zero and then returns a pointer to
calloc()
memory
free() deallocate the previously allocated space
realloc() Change the size of previously allocated space

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.

Example #1: Using C malloc() and free()


Write a C program to find sum of n elements entered by user. To perform this program,
allocate memory dynamically using malloc() function.
#include <stdio.h>
#include <stdlib.h>

int main()
{
int num, i, *ptr, sum = 0;

printf("Enter number of elements: ");


scanf("%d", &num);

ptr = (int*) malloc(num * sizeof(int)); //memory allocated using malloc


if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}

printf("Enter elements of array: ");


for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}

printf("Sum = %d", sum);


free(ptr);
return 0;
}

Example #2: Using C calloc() and free()


Write a C program to find sum of n elements entered by user. To perform this program,
allocate memory dynamically using calloc() function.
#include <stdio.h>
#include <stdlib.h>

int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);

ptr = (int*) calloc(num, sizeof(int));


if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}

printf("Enter elements of array: ");


for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}

printf("Sum = %d", sum);


free(ptr);
return 0;
}

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.

Example #3: Using realloc()


#include <stdio.h>
#include <stdlib.h>

int main()
{
int *ptr, i , n1, n2;
printf("Enter size of array: ");
scanf("%d", &n1);

ptr = (int*) malloc(n1 * sizeof(int));

printf("Address of previously allocated memory: ");


for(i = 0; i < n1; ++i)
printf("%u\t",ptr + i);

printf("\nEnter new size of array: ");


scanf("%d", &n2);
ptr = realloc(ptr, n2);
for(i = 0; i < n2; ++i)
printf("%u\t", ptr + i);
return 0;
}

You might also like