Computer Programming Unit 3

Size: px
Start display at page:

Download "Computer Programming Unit 3"

Transcription

1 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

2 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

3 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

4 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 = Address of i = Address of j = Address of j =

5 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

6 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

7 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

8 8

9 Accessing a variable to pointer Null Pointer 9

10 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

11 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

12 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

13 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= =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 14

15 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

16 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

17 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 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

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

19 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: 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

20 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

21 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

22 #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

23 #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

24 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

25 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

26 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

27 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: Enter Number 8: Enter Number 9: 5.67 Enter Number 10: Largest element:

28 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

29 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

30 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

31 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

32 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

33 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

34 #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

35 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

36 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

37 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 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: 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

38 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

39 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

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

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming Jagannath Institute of Management Sciences Lajpat Nagar BCA II Sem C Programming UNIT I Pointers: Introduction to Pointers, Pointer Notation,Decalaration and Initialization, Accessing variable through

More information

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

int marks[10]; // fixed size and fixed address No change in Memory address. Dynamic Memory Allocation : Used When we want to allocate memory during run time. int marks[10]; // fixed size and fixed address No change in Memory address. // fixed size. ( no change in size possible

More information

Dynamic Memory Allocation

Dynamic Memory Allocation Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility, there are four library routines known as memory management

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 9 Pointer Department of Computer Engineering 1/46 Outline Defining and using Pointers

More information

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1 C Pointers 1. Objective... 2 2. Introduction... 2 3. Pointer Variable Declarations and Initialization... 3 4. Reference operator (&) and Dereference operator (*) 6 5. Relation between Arrays and Pointers...

More information

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

Dynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1 Dynamic Memory Dynamic Memory Allocation Strings September 18, 2017 Hassan Khosravi / Geoffrey Tien 1 Pointer arithmetic If we know the address of the first element of an array, we can compute the addresses

More information

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

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS Syllabus: Pointers and Preprocessors: Pointers and address, pointers and functions (call by reference) arguments, pointers and arrays, address arithmetic, character pointer and functions, pointers to pointer,initialization

More information

Subject: Fundamental of Computer Programming 2068

Subject: Fundamental of Computer Programming 2068 Subject: Fundamental of Computer Programming 2068 1 Write an algorithm and flowchart to determine whether a given integer is odd or even and explain it. Algorithm Step 1: Start Step 2: Read a Step 3: Find

More information

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

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size]; Arrays An array is a collection of two or more adjacent memory cells, called array elements. Array is derived data type that is used to represent collection of data items. C Array is a collection of data

More information

Programming. Pointers, Multi-dimensional Arrays and Memory Management

Programming. Pointers, Multi-dimensional Arrays and Memory Management Programming Pointers, Multi-dimensional Arrays and Memory Management Summary } Computer Memory } Pointers } Declaration, assignment, arithmetic and operators } Casting and printing pointers } Relationship

More information

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Arrays and Pointers. CSE 2031 Fall November 11, 2013 Arrays and Pointers CSE 2031 Fall 2013 November 11, 2013 1 Arrays l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. 2 Arrays: Example

More information

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW IMPORTANT QUESTIONS IN C FOR THE INTERVIEW 1. What is a header file? Header file is a simple text file which contains prototypes of all in-built functions, predefined variables and symbolic constants.

More information

Unit IV & V Previous Papers 1 mark Answers

Unit IV & V Previous Papers 1 mark Answers 1 What is pointer to structure? Pointer to structure: Unit IV & V Previous Papers 1 mark Answers The beginning address of a structure can be accessed through the use of the address (&) operator If a variable

More information

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

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014. Arrays Arrays and Pointers l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. EECS 2031 Fall 2014 November 11, 2013 1 2 Arrays: Example

More information

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

First of all, it is a variable, just like other variables you studied Pointers: Basics What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the address (rather than the value)

More information

Variation of Pointers

Variation of Pointers Variation of Pointers A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before

More information

Dynamic memory allocation (malloc)

Dynamic memory allocation (malloc) 1 Plan for today Quick review of previous lecture Array of pointers Command line arguments Dynamic memory allocation (malloc) Structures (Ch 6) Input and Output (Ch 7) 1 Pointers K&R Ch 5 Basics: Declaration

More information

UNIT - V STRUCTURES AND UNIONS

UNIT - V STRUCTURES AND UNIONS UNIT - V STRUCTURES AND UNIONS STRUCTURE DEFINITION A structure definition creates a format that may be used to declare structure variables. Let us use an example to illustrate the process of structure

More information

Memory Allocation in C

Memory Allocation in C Memory Allocation in C When a C program is loaded into memory, it is organized into three areas of memory, called segments: the text segment, stack segment and heap segment. The text segment (also called

More information

MODULE 5: Pointers, Preprocessor Directives and Data Structures

MODULE 5: Pointers, Preprocessor Directives and Data Structures MODULE 5: Pointers, Preprocessor Directives and Data Structures 1. What is pointer? Explain with an example program. Solution: Pointer is a variable which contains the address of another variable. Two

More information

[0569] p 0318 garbage

[0569] p 0318 garbage A Pointer is a variable which contains the address of another variable. Declaration syntax: Pointer_type *pointer_name; This declaration will create a pointer of the pointer_name which will point to the

More information

Procedural programming with C

Procedural programming with C Procedural programming with C Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 77 Functions Similarly to its mathematical

More information

Memory Management. CSC215 Lecture

Memory Management. CSC215 Lecture Memory Management CSC215 Lecture Outline Static vs Dynamic Allocation Dynamic allocation functions malloc, realloc, calloc, free Implementation Common errors Static Allocation Allocation of memory at compile-time

More information

Pointers, Arrays, and Strings. CS449 Spring 2016

Pointers, Arrays, and Strings. CS449 Spring 2016 Pointers, Arrays, and Strings CS449 Spring 2016 Pointers Pointers are important. Pointers are fun! Pointers Every variable in your program has a memory location. This location can be accessed using & operator.

More information

School of Science and Technology

School of Science and Technology INTRODUCTION Pointers Unit 9 In the previous unit 8 we have studied about C structure and their declarations, definitions, initializations. Also we have taught importance of C structures and their applications.

More information

Memory Allocation. General Questions

Memory Allocation. General Questions General Questions 1 Memory Allocation 1. Which header file should be included to use functions like malloc() and calloc()? A. memory.h B. stdlib.h C. string.h D. dos.h 2. What function should be used to

More information

POINTER & REFERENCE VARIABLES

POINTER & REFERENCE VARIABLES Lecture 9 POINTER & REFERENCE VARIABLES Declaring data pointer variables Assignment operations with pointers Referring objects using pointer variables Generic pointers Operations with pointer variables

More information

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

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline CS 0 Lecture 8 Chapter 5 Louden Outline The symbol table Static scoping vs dynamic scoping Symbol table Dictionary associates names to attributes In general: hash tables, tree and lists (assignment ) can

More information

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7 Strings and Clases BIL104E: Introduction to Scientific and Engineering Computing Lecture 7 Manipulating Strings Scope and Storage Classes in C Strings Declaring a string The length of a string Copying

More information

UNDERSTANDING THE COMPUTER S MEMORY

UNDERSTANDING THE COMPUTER S MEMORY POINTERS UNDERSTANDING THE COMPUTER S MEMORY Every computer has a primary memory. All our data and programs need to be placed in the primary memory for execution. The primary memory or RAM (Random Access

More information

High Performance Programming Programming in C part 1

High Performance Programming Programming in C part 1 High Performance Programming Programming in C part 1 Anastasia Kruchinina Uppsala University, Sweden April 18, 2017 HPP 1 / 53 C is designed on a way to provide a full control of the computer. C is the

More information

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

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ... Why Pointers Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation. They provide support for dynamic data structures, such

More information

Pointers. Introduction

Pointers. Introduction Pointers Spring Semester 2007 Programming and Data Structure 1 Introduction A pointer is a variable that represents the location (rather than the value) of a data item. They have a number of useful applications.

More information

C Structures & Dynamic Memory Management

C Structures & Dynamic Memory Management C Structures & Dynamic Memory Management Goals of this Lecture Help you learn about: Structures and unions Dynamic memory management Note: Will be covered in precepts as well We look at them in more detail

More information

Lecture 5: Multidimensional Arrays. Wednesday, 11 February 2009

Lecture 5: Multidimensional Arrays. Wednesday, 11 February 2009 Lecture 5: Multidimensional Arrays CS209 : Algorithms and Scientific Computing Wednesday, 11 February 2009 CS209 Lecture 5: Multidimensional Arrays 1/20 In today lecture... 1 Let s recall... 2 Multidimensional

More information

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

In Java we have the keyword null, which is the value of an uninitialized reference type + More on Pointers + Null pointers In Java we have the keyword null, which is the value of an uninitialized reference type In C we sometimes use NULL, but its just a macro for the integer 0 Pointers are

More information

Tutorial 10 Pointers in C. Shuyue Hu

Tutorial 10 Pointers in C. Shuyue Hu Tutorial 10 Pointers in C Shuyue Hu Content Basic concept of pointers Pointer arithmetic Array of pointers Pointer to pointer Passing pointers to functions in C Return pointer from functions in C 2 Content

More information

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

Chapter 2 (Dynamic variable (i.e. pointer), Static variable) Chapter 2 (Dynamic variable (i.e. pointer), Static variable) August_04 A2. Identify and explain the error in the program below. [4] #include int *pptr; void fun1() { int num; num=25; pptr= &num;

More information

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

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017 Pointers (part 1) EECS 2031 25 September 2017 1 What are pointers? We have seen pointers before. scanf( %f, &inches );! 2 1 Example char c; c = getchar(); printf( %c, c); char c; char *p; c = getchar();

More information

POINTER AND ARRAY SUNU WIBIRAMA

POINTER AND ARRAY SUNU WIBIRAMA POINTER AND ARRAY SUNU WIBIRAMA Presentation Outline Basic Pointer Arrays Dynamic Memory Allocation Basic Pointer 3 Pointers A pointer is a reference to another variable (memory location) in a program

More information

dynamic memory allocation

dynamic memory allocation Dynamic memory allocation in C The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions

More information

Pointers and File Handling

Pointers and File Handling 1 Pointers and File Handling From variables to their addresses Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 2 Basics of Pointers INDIAN INSTITUTE OF TECHNOLOGY

More information

IV Unit Second Part STRUCTURES

IV Unit Second Part STRUCTURES STRUCTURES IV Unit Second Part Structure is a very useful derived data type supported in c that allows grouping one or more variables of different data types with a single name. The general syntax of structure

More information

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

Arrays. Example: Run the below program, it will crash in Windows (TurboC Compiler) 1 Arrays General Questions 1. What will happen if in a C program you assign a value to an array element whose subscript exceeds the size of array? A. The element will be set to 0. B. The compiler would

More information

Class Information ANNOUCEMENTS

Class Information ANNOUCEMENTS Class Information ANNOUCEMENTS Third homework due TODAY at 11:59pm. Extension? First project has been posted, due Monday October 23, 11:59pm. Midterm exam: Friday, October 27, in class. Don t forget to

More information

CS6202 - PROGRAMMING & DATA STRUCTURES UNIT I Part - A 1. W hat are Keywords? Keywords are certain reserved words that have standard and pre-defined meaning in C. These keywords can be used only for their

More information

Content. In this chapter, you will learn:

Content. In this chapter, you will learn: ARRAYS & HEAP Content In this chapter, you will learn: To introduce the array data structure To understand the use of arrays To understand how to define an array, initialize an array and refer to individual

More information

C PROGRAMMING Lecture 5. 1st semester

C PROGRAMMING Lecture 5. 1st semester C PROGRAMMING Lecture 5 1st semester 2017-2018 Program Address Space The Stack The stack is the place where all local variables are stored a local variable is declared in some scope Example int x; //creates

More information

Dynamic memory allocation

Dynamic memory allocation Dynamic memory allocation outline Memory allocation functions Array allocation Matrix allocation Examples Memory allocation functions (#include ) malloc() Allocates a specified number of bytes

More information

Q 1. Attempt any TEN of the following:

Q 1. Attempt any TEN of the following: Subject Code: 17212 Model Answer Page No: 1 / 26 Important Instructions to examiners: 1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme. 2) The

More information

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

C Tutorial. Pointers, Dynamic Memory allocation, Valgrind, Makefile - Abhishek Yeluri and Yashwant Reddy Virupaksha C Tutorial Pointers, Dynamic Memory allocation, Valgrind, Makefile - Abhishek Yeluri and Yashwant Reddy Virupaksha CS 370 - Operating Systems - Spring 2019 1 Outline What is a pointer? & and * operators

More information

Computers Programming Course 5. Iulian Năstac

Computers Programming Course 5. Iulian Năstac Computers Programming Course 5 Iulian Năstac Recap from previous course Classification of the programming languages High level (Ada, Pascal, Fortran, etc.) programming languages with strong abstraction

More information

Unit 7. Functions. Need of User Defined Functions

Unit 7. Functions. Need of User Defined Functions Unit 7 Functions Functions are the building blocks where every program activity occurs. They are self contained program segments that carry out some specific, well defined task. Every C program must have

More information

ARRAYS(II Unit Part II)

ARRAYS(II Unit Part II) ARRAYS(II Unit Part II) Array: An array is a collection of two or more adjacent cells of similar type. Each cell in an array is called as array element. Each array should be identified with a meaningful

More information

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

F.Y. Diploma : Sem. II [CO/CD/CM/CW/IF] Programming in C F.Y. Diploma : Sem. II [CO/CD/CM/CW/IF] Programming in C Time : 3 Hrs.] Prelim Question Paper Solution [Marks : 70 Q.1 Attempt any FIVE of the following : [10] Q.1 (a) List any four relational operators.

More information

Arrays and Pointers (part 1)

Arrays and Pointers (part 1) Arrays and Pointers (part 1) CSE 2031 Fall 2010 17 October 2010 1 Arrays Grouping of data of the same type. Loops commonly used for manipulation. Programmers set array sizes explicitly. 2 1 Arrays: Example

More information

Arrays and Pointers (part 1)

Arrays and Pointers (part 1) Arrays and Pointers (part 1) CSE 2031 Fall 2012 Arrays Grouping of data of the same type. Loops commonly used for manipulation. Programmers set array sizes explicitly. Arrays: Example Syntax type name[size];

More information

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

United States Naval Academy Electrical and Computer Engineering Department EC310-6 Week Midterm Spring AY2017 United States Naval Academy Electrical and Computer Engineering Department EC310-6 Week Midterm Spring AY2017 1. Do a page check: you should have 8 pages including this cover sheet. 2. You have 50 minutes

More information

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

Functions. (transfer of parameters, returned values, recursion, function pointers). Functions (transfer of parameters, returned values, recursion, function pointers). A function is a named, independent section of C/C++ code that performs a specific task and optionally returns a value

More information

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

CS2351 Data Structures. Lecture 7: A Brief Review of Pointers in C CS2351 Data Structures Lecture 7: A Brief Review of Pointers in C 1 About this lecture Pointer is a useful object that allows us to access different places in our memory We will review the basic use of

More information

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

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

More information

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

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018 Pointer Basics Lecture 13 COP 3014 Spring 2018 March 28, 2018 What is a Pointer? A pointer is a variable that stores a memory address. Pointers are used to store the addresses of other variables or memory

More information

CS201- Introduction to Programming Current Quizzes

CS201- Introduction to Programming Current Quizzes CS201- Introduction to Programming Current Quizzes Q.1 char name [] = Hello World ; In the above statement, a memory of characters will be allocated 13 11 12 (Ans) Q.2 A function is a block of statements

More information

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

CSE 2421: Systems I Low-Level Programming and Computer Organization. Functions. Presentation C. Predefined Functions CSE 2421: Systems I Low-Level Programming and Computer Organization Functions Read/Study: Reek Chapters 7 Gojko Babić 01-22-2018 Predefined Functions C comes with libraries of predefined functions E.g.:

More information

int Return the number of characters in string s.

int Return the number of characters in string s. 1a.String handling functions: Function strcmp(const char *s1, const char *s2) strcpy(char *s1, const char *s2) strlen(const char *) strcat(char *s1, Data type returned int Task Compare two strings lexicographically.

More information

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

Pointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays EE105: Software Engineering II Part 6 Pointers page 1 of 19 Part VI Pointers 1) Introduction 2) Declaring Pointer Variables 3) Using Pointers 4) Pointer Arithmetic 5) Pointers and Arrays 6) Pointers and

More information

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

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013 Lecture07: Strings, Variable Scope, Memory Model 4/8/2013 Slides modified from Yin Lou, Cornell CS2022: Introduction to C 1 Outline Review pointers New: Strings New: Variable Scope (global vs. local variables)

More information

EM108 Software Development for Engineers

EM108 Software Development for Engineers EE108 Section 6 Pointers page 1 of 20 EM108 Software Development for Engineers Section 6 - Pointers 1) Introduction 2) Declaring Pointer Variables 3) Using Pointers 4) Pointer Arithmetic 5) Pointers and

More information

MODULE V: POINTERS & PREPROCESSORS

MODULE V: POINTERS & PREPROCESSORS MODULE V: POINTERS & PREPROCESSORS INTRODUCTION As you know, every variable is a memory-location and every memory-location has its address defined which can be accessed using ampersand(&) operator, which

More information

Engineering program development 6. Edited by Péter Vass

Engineering program development 6. Edited by Péter Vass Engineering program development 6 Edited by Péter Vass Variables When we define a variable with its identifier (name) and type in the source code, it will result the reservation of some memory space for

More information

Government Polytechnic Muzaffarpur.

Government Polytechnic Muzaffarpur. Government Polytechnic Muzaffarpur. Name of the Lab: COMPUTER PROGRAMMING LAB (MECH. ENGG. GROUP) Subject Code: 1625408 Experiment: 1 Aim: Programming exercise on executing a C program. If you are looking

More information

PDS Class Test 2. Room Sections No of students

PDS Class Test 2. Room Sections No of students PDS Class Test 2 Date: October 27, 2016 Time: 7pm to 8pm Marks: 20 (Weightage 50%) Room Sections No of students V1 Section 8 (All) Section 9 (AE,AG,BT,CE, CH,CS,CY,EC,EE,EX) V2 Section 9 (Rest, if not

More information

CS61, Fall 2012 Section 2 Notes

CS61, Fall 2012 Section 2 Notes CS61, Fall 2012 Section 2 Notes (Week of 9/24-9/28) 0. Get source code for section [optional] 1: Variable Duration 2: Memory Errors Common Errors with memory and pointers Valgrind + GDB Common Memory Errors

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

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

P.E.S. INSTITUTE OF TECHNOLOGY BANGALORE SOUTH CAMPUS 1 ST INTERNAL ASSESMENT TEST (SCEME AND SOLUTIONS) FACULTY: Ms. Saritha P.E.S. INSTITUTE OF TECHNOLOGY BANGALORE SOUTH CAMPUS 1 ST INTERNAL ASSESMENT TEST (SCEME AND SOLUTIONS) SUBJECT / CODE: Programming in C and Data Structures- 15PCD13 What is token?

More information

C Tutorial Pointers, Dynamic Memory allocation, Makefile

C Tutorial Pointers, Dynamic Memory allocation, Makefile C Tutorial Pointers, Dynamic Memory allocation, Makefile -Abhishek Yeluri and Rejina Basnet 8/23/18 CS370 - Fall 2018 Outline What is a pointer? & and * operators Pointers with Arrays and Strings Dynamic

More information

C library = Header files + Reserved words + main method

C library = Header files + Reserved words + main method DAY 1: What are Libraries and Header files in C. Suppose you need to see an Atlas of a country in your college. What do you need to do? You will first go to the Library of your college and then to the

More information

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

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21 Department of Computer Science College of Engineering Boise State University September 11, 2017 1/21 Pointers A pointer is a variable that stores the address of another variable. Pointers are similar to

More information

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

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 Unti 4: C Arrays Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type An array is used to store a collection of data, but it is often more useful

More information

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

Language comparison. C has pointers. Java has references. C++ has pointers and references Pointers CSE 2451 Language comparison C has pointers Java has references C++ has pointers and references Pointers Values of variables are stored in memory, at a particular location A location is identified

More information

Chapter 3: Arrays and More C Functionality

Chapter 3: Arrays and More C Functionality Chapter 3: Arrays and More C Functionality Objectives: (a) Describe how an array is stored in memory. (b) Define a string, and describe how strings are stored. (c) Describe the implications of reading

More information

MODULE Z THE C STORAGE CLASSES, SCOPE AND MEMORY ALLOCATION

MODULE Z THE C STORAGE CLASSES, SCOPE AND MEMORY ALLOCATION MODULE Z THE C STORAGE CLASSES, SCOPE AND MEMORY ALLOCATION My Training Period: hours Note: gcc compilation examples are given at the end of this Module. Abilities: Understand and use the auto, register,

More information

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

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011 CS 61C: Great Ideas in Computer Architecture (Machine Structures) Introduction to C (Part II) Instructors: Randy H. Katz David A. Patterson http://inst.eecs.berkeley.edu/~cs61c/sp11 Spring 2011 -- Lecture

More information

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

Pointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables Chapter 11 Pointers The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into bytes, with each byte capable

More information

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

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee C Language Part 2 (Minor modifications by the instructor) 1 Scope Rules A variable declared inside a function is a local variable Each local variable in a function comes into existence when the function

More information

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

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100 Code: DC-05 Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100 NOTE: There are 11 Questions in all. Question 1 is compulsory and carries 16 marks. Answer to Q. 1. must be written in the space

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

UIC. C Programming Primer. Bharathidasan University

UIC. C Programming Primer. Bharathidasan University C Programming Primer UIC C Programming Primer Bharathidasan University Contents Getting Started 02 Basic Concepts. 02 Variables, Data types and Constants...03 Control Statements and Loops 05 Expressions

More information

Homework #3 CS2255 Fall 2012

Homework #3 CS2255 Fall 2012 Homework #3 CS2255 Fall 2012 MULTIPLE CHOICE 1. The, also known as the address operator, returns the memory address of a variable. a. asterisk ( * ) b. ampersand ( & ) c. percent sign (%) d. exclamation

More information

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

APS105. Malloc and 2D Arrays. Textbook Chapters 6.4, Datatype Size APS105 Malloc and 2D Arrays Textbook Chapters 6.4, 10.2 Datatype Size Datatypes have varying size: char: 1B int: 4B double: 8B int sizeof(): a builtin function that returns size of a type int x =

More information

INTRODUCTION 1 AND REVIEW

INTRODUCTION 1 AND REVIEW INTRODUTION 1 AND REVIEW hapter SYS-ED/ OMPUTER EDUATION TEHNIQUES, IN. Programming: Advanced Objectives You will learn: Program structure. Program statements. Datatypes. Pointers. Arrays. Structures.

More information

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

CS 137 Part 5. Pointers, Arrays, Malloc, Variable Sized Arrays, Vectors. October 25th, 2017 CS 137 Part 5 Pointers, Arrays, Malloc, Variable Sized Arrays, Vectors October 25th, 2017 Exam Wrapper Silently answer the following questions on paper (for yourself) Do you think that the problems on

More information

'C' Programming Language

'C' Programming Language F.Y. Diploma : Sem. II [DE/EJ/ET/EN/EX] 'C' Programming Language Time: 3 Hrs.] Prelim Question Paper Solution [Marks : 70 Q.1 Attempt any FIVE of the following : [10] Q.1(a) Define pointer. Write syntax

More information

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

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef today advanced data types (1) typedef. mon 23 sep 2002 homework #1 due today homework #2 out today quiz #1 next class 30-45 minutes long one page of notes topics: C advanced data types dynamic memory allocation

More information

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

PES INSTITUTE OF TECHNOLOGY (BSC) I MCA, First IA Test, November 2015 Programming Using C (13MCA11) Solution Set Faculty: Jeny Jijo PES INSTITUTE OF TECHNOLOGY (BSC) I MCA, First IA Test, November 2015 Programming Using C (13MCA11) Solution Set Faculty: Jeny Jijo 1. (a)what is an algorithm? Draw a flowchart to print N terms of Fibonacci

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

edunepal_info

edunepal_info facebook.com/edunepal.info @ edunepal_info C interview questions (1 125) C interview questions are given with the answers in this website. We have given C interview questions faced by freshers and experienced

More information

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

i location name 3 value at location 6485 location no.(address) POINTERS The & and * operators. Consider the declaration, int i = 3; i location name 3 value at location 6485 location no.(address) This declaration tells the C compiler to: (a)reserve space in memory

More information

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

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays C Arrays This handout was written by Nick Parlante and Julie Zelenski. As you recall, a C array is formed by laying out all the elements

More information

A Fast Review of C Essentials Part II

A Fast Review of C Essentials Part II A Fast Review of C Essentials Part II Structural Programming by Z. Cihan TAYSI Outline Fixed vs. Automatic duration Scope Global variables The register specifier Storage classes Dynamic memory allocation

More information