Computer Programming Unit 3

Similar documents
Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

int marks[10]; // fixed size and fixed address No change in Memory address.

Dynamic Memory Allocation

Fundamental of Programming (C)

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

Dynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS

Subject: Fundamental of Computer Programming 2068

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

Programming. Pointers, Multi-dimensional Arrays and Memory Management

Arrays and Pointers. CSE 2031 Fall November 11, 2013

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

Unit IV & V Previous Papers 1 mark Answers

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

First of all, it is a variable, just like other variables you studied

Variation of Pointers

Dynamic memory allocation (malloc)

UNIT - V STRUCTURES AND UNIONS

Memory Allocation in C

MODULE 5: Pointers, Preprocessor Directives and Data Structures

[0569] p 0318 garbage

Procedural programming with C

Memory Management. CSC215 Lecture

Pointers, Arrays, and Strings. CS449 Spring 2016

School of Science and Technology

Memory Allocation. General Questions

POINTER & REFERENCE VARIABLES

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7

UNDERSTANDING THE COMPUTER S MEMORY

High Performance Programming Programming in C part 1

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

Pointers. Introduction

C Structures & Dynamic Memory Management

Lecture 5: Multidimensional Arrays. Wednesday, 11 February 2009

In Java we have the keyword null, which is the value of an uninitialized reference type

Tutorial 10 Pointers in C. Shuyue Hu

Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

POINTER AND ARRAY SUNU WIBIRAMA

dynamic memory allocation

Pointers and File Handling

IV Unit Second Part STRUCTURES

Arrays. Example: Run the below program, it will crash in Windows (TurboC Compiler)

Class Information ANNOUCEMENTS


Content. In this chapter, you will learn:

C PROGRAMMING Lecture 5. 1st semester

Dynamic memory allocation

Q 1. Attempt any TEN of the following:

C Tutorial. Pointers, Dynamic Memory allocation, Valgrind, Makefile - Abhishek Yeluri and Yashwant Reddy Virupaksha

Computers Programming Course 5. Iulian Năstac

Unit 7. Functions. Need of User Defined Functions

ARRAYS(II Unit Part II)

F.Y. Diploma : Sem. II [CO/CD/CM/CW/IF] Programming in C

Arrays and Pointers (part 1)

Arrays and Pointers (part 1)

United States Naval Academy Electrical and Computer Engineering Department EC310-6 Week Midterm Spring AY2017

Functions. (transfer of parameters, returned values, recursion, function pointers).

CS2351 Data Structures. Lecture 7: A Brief Review of Pointers in C

(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

CS201- Introduction to Programming Current Quizzes

CSE 2421: Systems I Low-Level Programming and Computer Organization. Functions. Presentation C. Predefined Functions

int Return the number of characters in string s.

Pointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

EM108 Software Development for Engineers

MODULE V: POINTERS & PREPROCESSORS

Engineering program development 6. Edited by Péter Vass

Government Polytechnic Muzaffarpur.

PDS Class Test 2. Room Sections No of students

CS61, Fall 2012 Section 2 Notes

CS201 Some Important Definitions

P.E.S. INSTITUTE OF TECHNOLOGY BANGALORE SOUTH CAMPUS 1 ST INTERNAL ASSESMENT TEST (SCEME AND SOLUTIONS)

C Tutorial Pointers, Dynamic Memory allocation, Makefile

C library = Header files + Reserved words + main method

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

Language comparison. C has pointers. Java has references. C++ has pointers and references

Chapter 3: Arrays and More C Functionality

MODULE Z THE C STORAGE CLASSES, SCOPE AND MEMORY ALLOCATION

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

Pointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

CSCI 171 Chapter Outlines

UIC. C Programming Primer. Bharathidasan University

Homework #3 CS2255 Fall 2012

APS105. Malloc and 2D Arrays. Textbook Chapters 6.4, Datatype Size

INTRODUCTION 1 AND REVIEW

CS 137 Part 5. Pointers, Arrays, Malloc, Variable Sized Arrays, Vectors. October 25th, 2017

'C' Programming Language

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

PES INSTITUTE OF TECHNOLOGY (BSC) I MCA, First IA Test, November 2015 Programming Using C (13MCA11) Solution Set Faculty: Jeny Jijo

UNIT- 3 Introduction to C++

edunepal_info

i location name 3 value at location 6485 location no.(address)

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

A Fast Review of C Essentials Part II

Transcription:

POINTERS INTRODUCTION Pointers are important in c-language. Some tasks are performed more easily with pointers such as dynamic memory allocation, cannot be performed without using pointers. So it s very necessary to learn pointers and to become a perfect c programmer. As you know, every variable is a memory location and every memory location has address which is defined and accessed using ampersand (&) operator. #include<stdio.h> #include<conio.h> void main( ) int var1; int var2[10]; printf( Address of : %x, &var1); printf( Address of : %x, &var2); getch(); Pointers: pointer is a variable that stores address of another variable. Pointer are used to allocate memory dynamically i.e at runtime in c-language. Pointer variable might belonging to any of the data type such as int, float, char, double, short, e.t.c. Syntax : data_type * variable_name; Example : int *p; char * ch; Where * is used to denote the pointers. P is the pointer variable and not a normal variable. Key points to remember about pointer 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. 1

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. Pointer is more efficient in handling array and structure. It reduces the length of the program and execution time. 10 Pointers are one of the most distinct and exciting features of c-language. It provides power and flexibility to the language. DECLARING A POINTER A variable is a declared as a pointer that holds a memory address. Explanation: Syntax for pointer declaration Datatype *pointer_name; Data type: type of variable that pointer points to. Or data type whose value is stored in pointer name. Asterisk: it is called as indirection operator. It is also called as value at address operator. Pointer_Name: Must follow be all rules of variable. It Must be any c-identifier Ways of Declaring Pointer Variable: * can appears anywhere between Pointer_name and Data Type. int *p; or int* p; or int * p; 2

Example of Declaring Integer Pointer : int n = 20; int *ptr; Example of Declaring Character Pointer : char ch = 'A'; char *cptr; Example of Declaring Float Pointer : float fvar = 3.14; float *fptr; Example program for pointers in C: Initialization of Pointers or initializing pointers Pointer initialization is the process of assigning address of the variable to pointer variable. Pointer variable contains address of variable of same data type. In c-language address operator & is used to determine the address of variable i.e it is used to get the address of variable. int a=10; int *ptr; // pointer declaration ptr = &a; // pointer initialization 3

int *ptr = &a; // initialization & declaration %p is a control specifier, which is used for displaying the address in hex format. int *p1; double *p2; char *p3; float *p4; Note : if you need a pointer to store the address of integer variable, then the data type of pointer should be int. By using *pointer we can access the value of variable example : double a=10; double *p; p=&a; Accessing variable through pointer: We can access the value of pointer using the de-reference operator and address of variable can be printed using address operator. Program : accessing value and address of Pointer #include<stdio.h> main() int i = 3, *j, **k; j = &i; k = &j; printf("\naddress of i = %u", &i); printf("\naddress of i = %u", j); printf("\naddress of j = %u", &j); printf("\naddress of j = %u", k); Output : Address of i = 65524 Address of i = 65524 Address of j = 65522 Address of j = 65522 4

POINTER OPERATORS C Pointers Operators that are used with Pointers The operators & and * that are used with Pointers in C. The & operator is also known as Address of Operator. Pointer Operator in C Program : #include <stdio.h> int main() int num = 10; //Variable Initialization. int *p; //Pointer declaration. p = &num; //Assigning address of num to the pointer p printf("address of variable num is: %p", p); return 0; In order to create pointer to a variable we use * operator and to find the address of variable we use & operator. [box]don t Consider & and * operator as Logical AND and Multiplication Operator in Case of Pointer. Important Notes : 1. & operator is called as address Operator. 2. * is called as Value at address Operator. 3. Value at address Operator gives Value stored at Particular address. 4. Value at address is also called as Indirection Operator. 5

Pointer Operators : Live Program #include<stdio.h> int main() int n = 20; printf("\nthe address of n is %u",&n); printf("\nthe Value of n is %d",n); printf("\nthe Value of n is %d",*(&n)); Output: The address of n is 1002 The Value of n is 20 The Value of n is 20 6

Important point to note is: The data type of pointer and the variable must match, an int pointer can hold the address of int variable, and similarly a pointer declared with float data type can hold the address of a float variable. The * Operator is also known as Value at address operator. If you need a pointer to store the address of integer variable then the data type of the pointer should be int. Note: int *p1; /*Pointer to an integer variable*/ double *p2; /*Pointer to a variable of data type double*/ char *p3; /*Pointer to a character variable*/ float *p4; /*pointer to a float variable*/ double a = 10; double *p; p = &a; *p would give us the value of the variable a. The following statement would display 10 as output. printf("%d", *p); Similarly if we assign a value to *pointer like this: *p = 200; It would change the value of variable a. The statement above will change the value of a from 10 to 200. 7

8

Accessing a variable to pointer Null Pointer 9

PASSING POINTER TO A FUNCTION IN C PROGRAMMING (OR) PASSING POINTER AS FUNCTION PARAMETERS When we pass address to a function, the parameters receiving the address should be pointer. Just like any other argument, pointers can also be passed to a function as an argument. Let s take an example to understand how this is done. When pointer is passed to function as an argument, address of memory location is passed instead of value. This is because, pointers stores the location of the memory and not the value. This method is known as call by reference or call by address in c. 10

ACCESSING AN ARRAY USING POINTER: This program declares the array of five element and the elements of that array are accessed using pointer. As we know that array is collection of data items that belongings to same data type in c. By using pointers that can be declared and accessed very easily. When an array is declared, the compiler allocates a base address and sufficient amount of storage to contain all the elements of the array in contiguous memory locations. void main int *p,sum,i; int x[5]=5,9,6,3,7; i=0; p=x; sum=0; printf( Element \t Value \t Address \n\n ); while(i<5) printf( x[%d] %d %u \n, i, *p, p); sum=sum+*p; i++; p++; Printf( \n sum=%d\n, sum); Printf( \n &x[0]=%u\n, &x[0]); Printf( \n p= %u\n, p); ACCESSING STRING MEMBERS USING A POINTER A string is array of characters, terminated with a null characters. Similar to arrays, we can use a pointers to access the individual characters in a string. void main() char *name; int length; char *cptr = name; Name = DELHI ; while(*cptr!= \0 ) Printf( %c is stored at address %u\n,*cptr,cptr); cptr++; Length=cptr-name; Printf( length of the string = %d\n, Length); getch(); 11

POINTER EXPRESSION Arithmetic operations between two or more pointers are not possible. But pointers can be used to perform arithmetic operations on the value they point to Pointer expressions: pointer variables can be used in expressions like variables. For example if p1 and p2 are properly declared and initialized pointers, then these statements are valid. e.g: a = *p1 * *p2 / *p3; b = 10* - *p3 / *p2; Pointer increment is valid in c. Ex: P++ or p=p1+2 are valid statements. When pointer is incremented, it increases it value by length of the data type. It points to memory location or data type. (1) Characters 1 byte (2) integer 2 bytes (3) Float 4 bytes (4) double 8 bytes like other variables pointer variables can be used in expressions If p1 and p2 are properly declared and initialized pointers, then the following statements are valid: Y=*p1**p2; Sum=sum+*p1; Z=5*-*p2/ *p1; *p2=*p2+10; *p1=*p1+*p2; *p1=*p2-*p1; NOTE: In the third statement there is a blank space between / and * because the symbol /*is considered as beginning of the comment and therefore the statement fails. 2) if p1 and p2 are properly declared and initialized pointers then, C allows adding integers to a pointer variable. 12

Example: int a=5, b=10; int *p1,*p2; p1=&a; p2=&b; Now, P1=p1+1=1000+2=1002; P1=p1+2=1000+ (2*2) =1004; P1=p1+4=1000+ (2*4) =1008; P2=p2+2=3000+ (2*2) =3004; P2=p2+6=3000+ (2*6) =3012; Here addition means bytes that pointer data type hold are subtracted number of times that is subtracted to the pointer variable. 3) If p1 & p2 are properly declared and initialized, pointers then C allows to subtract integers from pointers. From the above example, P1=p1-1=1000-2=998; P1=p1-2=1000-4=996; P1=p1-4=1000-8=992; P2=p2-2=3000-4=2996; P2=p2-6=3000-12=2988; Here the subtraction means byte that pointer data type hold are subtracted number of times that is subtracted to the pointer variable. 4) If p1 & p2 are properly declared and initialize pointers, and both points to the elements of same type. Subtraction of one pointer from another pointer is also possible". 5) Pointer can also be used with increment and decrement operators. Ex: int a=10; int *b; b=&a; 13

14

Write a c program to show the effect of increment on pointers variables. Display the memory locations of integer, character, and floating point numbers before and after increment of pointers. Void main () int x, *x1; char y, *y1; float z, *z1; clrscr(); printf( Enter integer, character, float ); scanf( %d%c%f,&x,&y,&z); x1 = &x; y1 = &y; z1=&z; printf( Address of x= %u, x1); printf( Address of y= %u, y1); printf( Address of z= %u, z1); x++; y++; z++; printf( After Increment in Pointers ); printf( Address of x= %u, x1); printf( Address of y= %u, y1); printf( Address of z= %u, z1); printf( Size of Data types ); printf( value of x= %d, sizeof(x)); printf( value of y= %d, sizeof(y)); printf( value of z= %d, sizeof(z)); printf( Values of variables ); printf( value of x= %d, x); printf( value of y= %c, y); printf( value of z= %f, z); getch(); 15

POINTERS AND ARRAYS Array name itself is an address or pointer. It points to the address of the first element. The elements of the array together with their address can be displayed by using name itself. Array elements are always stored in contiguous memory locations. When an array is declared, compiler allocates sufficient amount of memory to contain all the elements of the array. Base address i.e address of the first element of the array 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 bytes, the five elements will be stored as follows: 16

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. In short, arr has two purpose - it is the name of an array and it acts as a pointer pointing towards the first element in the array. arr is equal to &arr[0] //by default We can declare a pointer of type int to point to the array arr. 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. POINTERS AND TWO-DIMENSIONAL ARRAYS A matrix can represent two dimensional elements of an array. Here, the argument of row number and second column number. To display the elements of two-dimensional array using pointer it is essential to have & operator as pre-fix with an array name followed by elements, otherwise compiler shows an error. Write a program to display array elements and their address using pointers. 4.22 17

ARRAY OF POINTERS C language also supports array of pointers. It is nothing but a collection of addresses. Here we store address of variables for which we have to declare an array as a pointer. We can also have array of pointers. Pointers are very helpful in handling character array with rows of varying length. Write a program to store addresses of different elements of an array-using array of pointers. 4.25 MULTIPLE INDIRECTIONS (POINTERS TO POINTERS) C allows the pointer to point to another pointer. It has declaration is similar to normal pointer but have more asterisk sign before them. 18

Normally, a pointer contains address of variable. When we define a pointer to pointer, the first pointer contains the address of the second pointer, which points to the location that contains actual value. Pointer is known as a variable containing address of another of another variable. The pointer variable also has an address. The pointer variable containing address of another pointer variable is called as pointer to pointer. Ex: **p; #include <stdio.h> o/p: 454 454 int main() int x, *p, **ptp; x=454; p=&x; ptp=&p; printf("%d %d",*p,**ptp); return 0; VOID POINTERS Pointer can also be declared as void type. Void pointer cannot be dereferencing without explicit type conversion. This is because, being void the compiler cannot determine the size of the object that points to, though void pointer declaration is possible, void variables declaration is not allowed. 4.38 19

MEMORY ALLOCATION There are two types of memory allocation Static memory Dynamic memory Static memory Allocation Memory is allocated at compile time that is called static memory. Every static variable comes under static variable. int arr[5]. Here it is fixed number of integer s elements stored using array. It comes under static memory. Here we cannot store sixth element of array. So it is called static array. Because these are comes under fixed size. Dynamic memory Allocation The process of memory allocation during program execution is called dynamic memory allocation. The only way to allocated dynamically memory through pointers. Dynamic memory Allocation means size of array and variable will increase and decreased using pointers that is called dynamic memory allocation. C language does not have any technique to allocate memory dynamically there are 4 library functions under stdlib.h for dynamic memory allocation. malloc( ) calloc ( ) realloc( ) free( ) 20

malloc() function in C: malloc () function is used to allocate space in memory during the execution of the program. malloc () does not initialize the memory allocated during execution. It carries garbage value. malloc () function returns null pointer if it couldn t able to allocate requested amount of memory. malloc() function is used for allocating block of memory at runtime. This function reserves a block of memory of given size and returns a pointer of type void. This means that we can assign it to any type of pointer using typecasting. If it fails to allocate enough space as specified, it returns a NULL pointer. Syntax: void* malloc(byte-size) Example using malloc() : int *x; x = (int*)malloc(50 * sizeof(int)); //memory space allocated to variable x free(x); //releases the memory allocated to variable x 21

#include <stdio.h> #include <string.h> #include <stdlib.h> int main( ) char *mem_allocation; /* memory is allocated dynamically */ mem_allocation = malloc( 20 * sizeof(char) ); if( mem_allocation== NULL ) printf("couldn't able to allocate requested memory\n"); else strcpy( mem_allocation,"king college of engineering "); printf("dynamically allocated memory content : " \ "%s\n", mem_allocation ); free(mem_allocation); Output Dynamically allocated memory content : king college of engineering 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. By using calloc() we can create the memory dynamically at initial stage. calloc() required 2 arguments of type count, size-type. Count will provide number of elements; size-type is data type size. calloc() will creates the memory in blocks format. Initial value of the memory is zero. Syntax void *calloc(number of items, element-size) ptr=(cast-type*)calloc(number, byte-size) ; 22

#include <stdio.h> #include <string.h> #include <stdlib.h> int main() char *mem_allocation; /* memory is allocated dynamically */ mem_allocation = calloc( 20, sizeof(char) ); if( mem_allocation== NULL ) printf("couldn't able to allocate requested memory\n"); else strcpy( mem_allocation,"king college of engineering"); printf("dynamically allocated memory content : " \ "%s\n", mem_allocation ); free(mem_allocation); Output: Dynamically allocated memory content : king college of engineering realloc() function in C: realloc () function modifies the allocated memory size by malloc () and calloc () functions to new size. If enough space doesn t exist in memory of current block to extend, new block is allocated for the full size of reallocation, then copies the existing data to new block and then frees the old block. By using realloc() we can create the memory dynamically at middle stage. Generally by using realloc() we can reallocation the memory. Realloc() required 2 arguments of type void*, size_type. Void* will indicates previous block base address, size-type is data type size. Realloc() will creates the memory in bytes format and initial value is garbage. Syntax void* realloc(pointer, new-size) 23

Example using realloc() : int *x; x=(int*)malloc(50 * sizeof(int)); x=(int*)realloc(x,100); //allocated a new memory to variable x #include <stdio.h> #include <string.h> #include <stdlib.h> int main() char *mem_allocation; /* memory is allocated dynamically */ mem_allocation = malloc( 20 * sizeof(char) ); if( mem_allocation == NULL ) printf("couldn't able to allocate requested memory\n"); else strcpy( mem_allocation,"fresh2refresh.com"); printf("dynamically allocated memory content : " \ "%s\n", mem_allocation ); mem_allocation=realloc(mem_allocation,100*sizeof(char)); if( mem_allocation == NULL ) printf("couldn't able to allocate requested memory\n"); else strcpy( mem_allocation,"space is extended upto " \ "100 characters"); printf("resized memory : %s\n", mem_allocation ); free(mem_allocation); Output Dynamically allocated memory content : fresh2refresh.com Resized memory : space is extended upto 100 characters 24

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 programs Example 2: Using C calloc() and free() #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; 25

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; Example 1: Using C malloc() and free() #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; 26

Example: Find Largest Element Using Dynamic Memory Allocation - calloc() #include <stdio.h> #include <stdlib.h> int main( ) int i, num; float *data; printf("enter total number of elements(1 to 100): "); scanf("%d", &num); // Allocates the memory for 'num' elements. data = (float*) calloc(num, sizeof(float)); if(data == NULL) printf("error!!! memory not allocated."); exit(0); printf("\n"); // Stores the number entered by the user. for(i = 0; i < num; ++i) printf("enter Number %d: ", i + 1); scanf("%f", data + i); // Loop to store largest number at address data for(i = 1; i < num; ++i) // Change < to > if you want to find the smallest number if(*data < *(data + i)) *data = *(data + i); printf("largest element = %.2f", *data); return 0; Output Enter total number of elements(1 to 100): 10 Enter Number 1: 2.34 Enter Number 2: 3.43 Enter Number 3: 6.78 Enter Number 4: 2.45 Enter Number 5: 7.64 Enter Number 6: 9.05 Enter Number 7: -3.45 Enter Number 8: -9.99 Enter Number 9: 5.67 Enter Number 10: 34.95 Largest element: 34.95 27

PROBLEMS WITH POINTERS Dangling pointers Memory leaks Double-deallocation/heap corrupting Dangling pointers: A pointer pointing to a memory location that has been deleted (or freed) is called dangling pointer. 1. Dangling pointers arise when an object is deleted or de-allocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the de-allocated memory. 2. In short pointer pointing to non-existing memory location is called dangling pointer. Example // The pointer pointing to local variable becomes // dangling when local variable is static. #include<stdio.h> int *fun() // x is local variable and goes out of // scope after an execution of fun() is // over. int x = 5; return &x; // Driver Code int main( ) int *p = fun(); fflush(stdin); // p points to something which is not // valid anymore printf("%d", *p); return 0; Output: A garbage Address The above problem doesn t appear (or p doesn t become dangling) if x is a static variable. 28

MEMORY LEAKS Memory leaks In computer science, a memory leak occurs when a computer program incorrectly manages memory allocations. Memory leak occurs when programmers create a memory in heap and forget to delete it. Memory leaks are particularly serious issues for programs like daemons and servers which by definition never terminate. MEMORY OVERWRITE /* Function with memory leak */ #include <stdlib.h> void f() int *ptr = (int *) malloc(sizeof(int)); /* Do some work */ return; /* Return without freeing ptr*/ Since p has been allocated to 10 bytes, if some code snippet tries to write a value to p that is 11 bytes, then this operation will silently, without telling you, eat up one byte from some other location. Let's assume pointer q represents this memory. Figure 2. Original contents of q Figure 3. Overwritten contents of q As a result, the pointer q will have contents that were never expected. Even if your module is coded well, it might behave incorrectly due to a coexisting module doing some memory overwriting. The example code snippet below can also explain this scenario. char *name = (char *) malloc(11); Assign some value to name memcpy ( p,name,11); // Problem begins here 29

In this example, the memcpy operation is trying to write 11 bytes to p, whereas it has been allocated only 10 bytes. Heap memory corrupt: Attempting to free memory already freed. Freeing memory that was not allocated. Attempting to read/write memory already freed. Attempting to read/write to memory which was never allocated. Memory allocation error. Reading/writing to memory out of the bounds of a dynamically allocated array UNDERSTANDING THE SCOPE OF FUNCTIONS Scope: the scope refers to the visibility of variables. In other words, the scope of variable defines the section of code in which variable is visible scope of variable can be broadly categorized in to three categories. Local scope Global scope Function scope Local variables or Local Scope Variables that are declared inside a function or block are called local variables. The variables which are declared inside function definition are called local variables. By using the local variables, we can access the particular function only. Ex: Local variable is a variable, which is declared inside the main( ) int main () int a, b, c; /* local variable declaration */ a = 10; /* actual initialization */ b = 20; c = a + b; printf ("value of a = %d, b = %d and c = %d\n", a, b, c); return 0; 30

Global Variables The variables which are declared outside of the function definition are called global variable. A global variable can be used in all functions. Global variables are defined outside a function, usually on top of the program. Global variables hold their values throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program. A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. #include <stdio.h> int g; /* global variable declaration */ int main () int a, b; /* local variable declaration */ a = 10; /* actual initialization */ b = 20; g = a + b; printf ("value of a = %d, b = %d and g = %d\n", a, b, g); return 0; SCOPE RULES A scope in C is a region of the program where the defined variable can have its existence and beyond that, variable can't be accessed. In C programming, Scope of an identifier is the part of the program where the identifier may directly be accessible. C scope rules tells rule of the scope of a variable that what is the scope of that variable. For example, local scope, global scope or just a formal parameters. The scope of a variable is a set of statements or block of statements Types of scope: A scope may be three types Block scope Function scope Program scope 31

Block scope: A Block is a set of statements enclosed within left and right braces ( and respectively). Blocks may be nested in C (a block may contain other blocks inside it). A variable declared in a block is accessible in the block and all inner blocks of that block, but not accessible outside the block. int main( ) int x = 10, y = 20; // The outer block contains declaration of x and y, so // following statement is valid and prints 10 and 20 printf("x = %d, y = %d\n", x, y); // y is declared again, so outer block y is not accessible // in this block int y = 40; x++; // Changes the outer block variable x to 11 y++; // Changes this block's variable y to 41 printf("x = %d, y = %d\n", x, y); // This statement accesses only outer block's variables printf("x = %d, y = %d\n", x, y); return 0; Output: x = 10, y = 20 x = 11, y = 41 x = 11, y = 20 Block Scope i.e Local Scope of variable is used to evaluate expression at block level. Variable is said to have local scope / block scope if it is defined within function or local block. In short we can say that local variables are in block scope. Important Points about Block Scope: 1. Block Scope is also called Local Scope. 2. It can be used only within a function or a block. 3. It is not visible outside the block. 4. Variables defined within local scope are called as Local variables. Function scope: A label (and only a label) declared inside a function is in scope everywhere in that function, in all nested blocks, before and after its own declaration. Note: a label is declared implicitly, by using an otherwise unused identifier before the colon character before any statement. 32

void f() goto label; // label in scope even though declared later label: goto label; // label ignores block scope void g() goto label; // error: label not in scope in g() A function itself is a block. Parameters and local variables of function follow the same block scope rules. Program scope: When variables are declared in the function and all those variables are valid within a function. These variables are unknown to other functions in program. Global variables and local variables are valid in entire program. Type qualifiers The keywords which are used to modify the properties of a variable are called type qualifiers. In C programming language, type qualifiers are the keywords used to modify the properties of variables. Using type qualifiers, we can change the properties of variables. C programming language provides two type qualifiers and they are as follows. const volatile 1. CONST KEYWORD: Constants are also like normal variables. But, only difference is, their values can t be modified by the program once they are defined. They refer to fixed values. They are also called as literals. They may be belonging to any of the data type. 33

#include <stdio.h> #include<conio.h> void main() int i = 9 ; const int x = 10 ; clrscr() ; i = 15 ; x = 100 ; // creates an error printf("i = %d\nx = %d", i, x ) ; Syntax: const data_type variable_name; (or) const data_type *variable_name; Please refer C Constants topic in this tutorial for more details on const keyword. 2. VOLATILE KEYWORD: When a variable is defined as volatile, the program may not change the value of the variable explicitly. But, these variable values might keep on changing without any explicit assignment by the program. These types of qualifiers are called volatile. For example, if global variable s address is passed to clock routine of the operating system to store the system time, the value in this address keep on changing without any assignment by the program. These variables are named as volatile variable. Syntax: volatile data_type variable_name; (or) volatile data_type *variable_name; C Storage Class Specifiers Storage class specifiers in C language tells the compiler where to store a variable, how to store the variable, what is the initial value of the variable and life time of the variable. Every variable in C programming has two properties: type and storage class. 34

Type refers to the data type of a variable. And, storage class determines the scope and lifetime of a variable. There are 4 types of storage class: 1. automatic 2. external 3. register 4. static Local Variable or Automatic (Auto) : keyword is auto The variables declared inside the function are automatic or local variables. The scope of this auto variable is within the function only. It is equivalent to local variable. All local variables are auto variables by default. #include<stdio.h> void increment(void); int main( ) increment(); increment(); increment(); increment(); return 0; void increment(void) auto int i = 0 ; printf ( "%d ", i ) ; i++; Output 0 0 0 0 35

2. Example program for extern variable in C: The scope of this extern variable is throughout the main program. It is equivalent to global variable. Definition for extern variable might be anywhere in the C program. #include<stdio.h> int x = 10 ; int main( ) extern int y; printf("the value of x is %d \n",x); printf("the value of y is %d",y); return 0; int y=50; Output : The value of x is 10 The value of y is 50 3.Example program for register variable in C: Register variables are also local variables, but stored in register memory. Whereas, auto variables are stored in main CPU memory. Register variables will be accessed very faster than the normal variables since they are stored in register memory rather than main memory. But, only limited variables can be used as register since register size is very low. (16 bits, 32 bits or 64 bits) #include <stdio.h> int main() register int i; int arr[5];// declaring array arr[0] = 10;// Initializing array arr[1] = 20; arr[2] = 30; arr[3] = 40; arr[4] = 50; 36

for (i=0;i<5;i++) // Accessing each variable printf("value of arr[%d] is %d \n", i, arr[i]); return 0; Output : value of arr[0] is 10 value of arr[1] is 20 value of arr[2] is 30 value of arr[3] is 40 value of arr[4] is 50 4. Example program for static variable in C: Static variables retain the value of the variable between different function calls. //C static example #include<stdio.h> void increment(void); int main() increment(); increment(); increment(); increment(); return 0; void increment(void) static int i = 0 ; printf ( "%d ", i ) ; i++; Output: 0 1 2 3 Return Statement: A function may or may not return a value. A return statement returns a value to the calling function and assigns to the variable in the left side of the calling function. 37

If a function does not return a value, the return type in the function definition and declaration is specified as void. The return statement is used to return some value or simply pass the control to the calling function. The return statement can be used in the following two ways. 1. return; 2. return expression; The first form of the return statement is used to terminate the function and pass the control to the calling function. No value from the called function is returned when this form of the return statement is used. The following program demonstrates the use of the first form of the return statement. #include <stdio.h> #include <conio.h> void function1(); void function2(); int function3(); int function4(); int main( ) int i; clrscr(); function1(); function2(); i=function3(); printf( Returned value = %d\n,i); printf( Returned value = %d\n, function4()); getch(); return 0; // mission completed return to OS 38

void function1( ) Printf( First \n ); void function2( ) printf( Second \n ); return; int function3( ) printf( Third 1\n ); return 0; printf( Third 2\n ); int function4( ) printf( Fourth\n ); return 0; 39