Solution: A pointer is a variable that holds the address of another object (data item) rather than a value.

Similar documents

Chapter-11 POINTERS. Important 3 Marks. Introduction: Memory Utilization of Pointer: Pointer:

Homework #3 CS2255 Fall 2012

Kapi ap l S e S hgal P T C p t u er. r S. c S ienc n e A n A k n leshw h ar ar Guj u arat C C h - 8

Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. Here are a few examples:

CHAPTER 4 FUNCTIONS. 4.1 Introduction

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

Procedural programming with C

UNIT- 3 Introduction to C++

C++ for Java Programmers

Downloaded from

What is an algorithm?

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

Darshan Institute of Engineering & Technology for Diploma Studies

Subject: Fundamental of Computer Programming 2068

CS201 Some Important Definitions

by Pearson Education, Inc. All Rights Reserved.

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

Outline. Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary

Functions. Introduction :

OOP THROUGH C++(R16) int *x; float *f; char *c;

What is Pointer? Pointer is a variable that holds a memory address, usually location of another variable.

CS201- Introduction to Programming Current Quizzes

Mechatronics and Microcontrollers. Szilárd Aradi PhD Refresh of C

Exam 3 Chapters 7 & 9

Pointers. Introduction

DECLARAING AND INITIALIZING POINTERS

Programming. C++ Basics

I Internal Examination Sept Class: - BCA I Subject: - Principles of Programming Lang. (BCA 104) MM: 40 Set: A Time: 1 ½ Hrs.

C++ Programming Chapter 7 Pointers

Pointers. Pointers. Pointers (cont) CS 217

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

Introduction to Computer Science Midterm 3 Fall, Points

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

Arrays and Pointers (part 1)

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

Advanced C Programming and Introduction to Data Structures

Short Notes of CS201

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

Lecture 16. Daily Puzzle. Functions II they re back and they re not happy. If it is raining at midnight - will we have sunny weather in 72 hours?

CS201 - Introduction to Programming Glossary By

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

Arrays, Pointers and Memory Management

Pointer Data Type and Pointer Variables

Computer Programming Unit 3

Arrays and Pointers (part 1)

CENG 447/547 Embedded and Real-Time Systems. Review of C coding and Soft Eng Concepts

Creating a C++ Program

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Introduction to Scientific Computing and Problem Solving

Pointers and Arrays 1

C++ is case sensitive language, meaning that the variable first_value, First_Value or FIRST_VALUE will be treated as different.

Fundamental of Programming (C)

CS201 Latest Solved MCQs

Basic Source Character Set for C++ Language:

DELHI PUBLIC SCHOOL TAPI

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

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

Downloaded S. from Kiran, PGT (CS) KV, Malleswaram STRUCTURES. Downloaded from

Algorithms & Data Structures

[0569] p 0318 garbage

Pointers, Dynamic Data, and Reference Types

UNDERSTANDING THE COMPUTER S MEMORY

Multiple Choice Questions ( 1 mark)

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Memory and Addresses. Pointers in C. Memory is just a sequence of byte-sized storage devices.

Pointers and File Handling

Pointers. A pointer value is the address of the first byte of the pointed object in the memory. A pointer does not know how many bytes it points to.

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

At the end of this module, the student should be able to:

C++ 8. Constructors and Destructors


C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

Memory Allocation in C

Chapter-13 USER DEFINED FUNCTIONS

Object Oriented Programming. Solved MCQs - Part 2

Basics of Programming

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1

Chapter-14 STRUCTURES

COMMON QUARTERLY EXAMINATION SEPTEMBER 2018

Input And Output of C++

2. Distinguish between a unary, a binary and a ternary operator. Give examples of C++ operators for each one of them.

A First Program - Greeting.cpp

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

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

Aryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9


PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Electronics and Communication

COMPUTER APPLICATION

Sir Syed University of Engineering and Technology. Computer Programming & Problem Solving ( CPPS ) Pointers. Chapter No 7

C++ character set Letters:- A-Z, a-z Digits:- 0 to 9 Special Symbols:- space + - / ( ) [ ] =! = < >, $ # ; :? & White Spaces:- Blank Space, Horizontal

Model Viva Questions for Programming in C lab

MYcsvtu Notes LECTURE 34. POINTERS

UNIT - V STRUCTURES AND UNIONS

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

LSN 3 C Concepts for OS Programming

Review of the C Programming Language for Principles of Operating Systems

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

Transcription:

1. What is a pointer? A pointer is a variable that holds the address of another object (data item) rather than a value. 2. What is base address? The address of the nth element can be represented as (a+n-1) where a is the base address of the array. 3. Explain the operators used to represent pointers. The address operation (&) The indirection operator (*) 4. Is arr[3] and *(a+3) the same? Yes, both are the same. 5. What is the use of operator? "Arrow operator ( ) - to refer to the structure elements. 6. Can a pointer be nested in a structure? Yes, pointers can be nested in structures. 7. Can we do the operation arr++ if arr is an array? No, it is not possible to perform incrementation operation on an array. 8. What is a call by value? If a variable is passed by value, then the changes to the corresponding data item will not be reflected in the calling program. 9. Does the array name carry the address of the first memory location? 1

Yes, array name carries the address of the first memory location. If a is a one dimensional array, then the address of the first element is expressed as &a[0] is simple a. 10. Write a program to explain a passing pointer as address to function. Main () Int num[] = 1,2,3,4,5p,I; For (i=0 ;I <5 ; i++) P =sum (&num[i]); Cout<<"the sum is "<<p; Getch (); Sum (int *n); Static int s=0; St = *n; Return (s); 11. What are the advantages of using the function object? Advantages in using a function object instead of pointers to functions or pointers to members. 1. Function objects are more flexible to design changes, because the object can be modified internally without changing its external interface. 2. In ordinary functions - prototypes remain intact when their implementation changes. 3. A function object may contain data members that store its state, thereby eliminating the need of external variables and complex argument lists. 2

4. Function objects present another benefit in regard to performance. Compilers are usually able to inline when a function call is made through a function object, thus optimizing your code. 5. It is difficult to inline - a function call made through a pointer. 12. State an example for function objects? This example demonstrates how an object can be made an argument of a function. #include <iostream.h> struct Paper double Width; ; double Height; void MagazineCover(Paper ppr) cout << "Characteristics of this piece of paper"; cout << "\nwidth = " << ppr.width; cout << "\nheight = " << ppr.height; cout << "\nperimeter = " << 2 + (ppr.width + ppr.height); cout << "\narea = " << ppr.width * ppr.height; int main(int argc, char* argv[]) double w, h; cout << "Provide the dimensions of the magazine cover\n"; cout << "Width: "; cin >> w; cout << "Height: "; 3

cin >> h; Paper Cover = w, h; MagazineCover(Cover); getchar(); return 0; 13. How are pointers and structures related? A pointer can point to a structure in the same way as it is used with the other variables. Thus pointers are called structure pointers. Syntax for declaring structure pointers is as follows: Struct [tag] Member 1; Member 2 ;..; Member n ; < variable list >, * ptr var ; Ptr serves as pointer variable pointing to the beginning of structure. Members of structure are accessed using the arrows operator ( ) # include < stdio.h > main ( ) struct emprec int eno; char ename[15]; 4

char design[10]; float basic; ; static struct emprec rec1 = 2234, "clinton", "clerk",3500.00; struct emprec *ptr; ptr=&rec1; clrscr(); cout<<"\n from structure \n"; cout<<"emp no : \n"<<rec1.eno; cout<<"emp name : \n"<< rec1.ename; cout<<"destignation : \n"<< rec1.design; cout<<" basic pay : \n "<<rec 1. basic); cout<<"\n from structure pointer \n "; cout<<"emp no : \n "<< ptr eno); cout<<"emp name : \n "<<ptr ename); cout<<"designation :\n"<<ptr design); cout<<"basic pay: \n"<<ptr basic); getch( ); o/p : from structure. emp no : 2234 emp name : clinton designation : clerk basic pay: 3500.00 from structure pointer 5

emp no : 2234 emp name : clinton designation : clerk basic pay: 3500.00 In above program, * ptr is a pointer to the structure emprec. The structure pointer *ptr is assigned the base address of structure variable rec1. The output statements that are used to print values "From structure pointers" have been discussed. The output statements that are used to print value "From structure pointer " are different as they use " arrow operator ( ) to refer to the structure elements. On the left hand side of the dot operator (. ), we should always use a structure variable, where as on the left hand side of the arrow operator, we should only use a pointer to a structure. Since the values of the structure members are sorted contiguously in the memory locations, the pointer to the structure will hold the base address of the structure, which is address of the first element. With this base address, the values of other members can be accessed by incrementing value of pointer variable depending upon the data type stored at a referred location. The diagrammatic arrangement of the structure variable and the pointer to structure in memory is illustrated as follows: Rec1.no rec 1. name rec 1. design rec 1. basic 2234 CLINTON CLERK 3500.00 2400 2402 2417 2427 ptr 2400 4024 In above figure, pointer to structure * ptr holds the base address of the structure, that is 2400. To move to the next members, it is enough to add the memory requirements of the current data type with a base address. As the memory requirement for an int data type is 2, compiler increments 2 bytes to the base address to move to the next location (ie 2400 + 2 = 2402). Here 2402 is the starting address in the above structure definition. A structure containing bit fields can be used within another structure as they are treated just like any other member. 14. Can we pass an entire array to a function? In this, we have to pass the base address (that is the address of the first array element) long with the size of the array to the called function. 6

Main () int num[]=1,2,3,4,5,p; P=sum (&num [0],5); Cout<<"the sum is"<<p; Getch (); Sum (int *n, int, count) Int i,s=0; For (i=0; i<count; i++) S+=*(n+i); Return (s); 15. Write a note on default arguments. C++ allows us to assign default values to a function s parameter which is useful in case a matching argument is not passed in the function call statement. The default values are specified at the time of function declaration. #include<iostream.h> void main( ) int sm(int a,int b,int c); int add(int a,int b=6); int m,n,l; cin>>m>>n>>l; sum(m,n); -fn call the argument can be avoided sum(m,n,l);-fn call all arguments can also be used 7

add(m); cout<<sum(m,b) int sum (int a,int b,int c=5) return(a+b+c); int add(int a,int b=6) return(a+b); The default arguments should appear as the last argument of the list of arguments. #include<iostream.h> inline float multi(float x,float y,float z=5.5) return(x*y*z): void main( ) void add (int &a,int &b) int m,n; cin>>m>>n; add(m,n); int l,k; cin>>l>>k; cout<<multi (l,k); 8

void add(int &a,int &b)] int t; t=a+b; cout<<t; 16. Explain pass by reference and call by reference. CALL BY REFERENCE:- In this case, the addresses of the actual arguments in the function call are passed to the parameters of the formal argument of the called function. i.e, changer () since the addresses are copied by the formal arguments, whatever changes that are made to the contents of these memory addresses which will be carried over to the main () function at the time of returning the control. Memory location of i and j From the figure, it is clear that the memory locations (addresses) 3284 and 3286 of the variables I and j respectively are passed to the changer () function. These addresses are copied by the pointer variables a and b respectively. These two variables now point to the integer values that are stored in the memory locations 3284 and 3286. If the swapping procedure takes place using the temporary variable temp, the values are directly returned to the memory addresses of I and j. When the control is transferred back to the calling programs the interchanged value will be retained. Pass By Reference The call by reference method uses a different mechanism. In place of passing a value to the function being called, a reference to the original variables is passed. Remember that a reference is an alias 9

(i.e., a different name) for a predefined variable. That is, the same variable value can be accessed by any of the two names: the original variables name and the reference name. When a function is called by reference, then, the formal parameters become references (or aliases) to the actual parameters in the calling function. This means that in the call by reference method, the called function does not create its own copy of original values; rather, it refers to the original values only by different names i.e., the references. Thus, the called function works with the original data and any change in the values gets reflected to the data. The call by reference method is useful in situations where the values of the original variables are to be changed using a function. The function change ( ) of program when called by reference will work in the desired manner. WORKING OF CALL BY REFERENCE METHOD OF A FUNCTION WORKING: #include<iostream.h> #include<conio.h> int main ( ) clrscr ( ); void change ( int &); \\ notice prototype int orig =10; \\ original value is 10 cout<< " the original value is : " <<orig << "\n"; change (orig); cout<<"value after change ( ) is over : "<<orig << "\n"; return 0; void change (int &a) a=20; cout<<"value of orig in function change ( ) is :"<< a<<"\n"; return; The above program will produce the following output. 10

The original value is 10 Value of orig in function change ( ) is: 20 Value after change ( ) is over : 20 In the above program change ( ) refers to the original value orig which is (10) by its reference a. As the same memory location is being referred to as orig by main () and as a by change ( ). So the charge in a (to 20) is done in the same location as that of orig s and hence, this change is reflected back to main ( ).Thus, the above output is produced. Void swap(int &a,int&b) int t=a; a=b; b=t; swap(m,n); void swap(int &a,int &b) int t=a; a=b; b=t; Memory used efficiently 17. Write a note on const pointers. Const keyword is used for declaring symbolic constants. We can also declare constant pointers or pointers to constants. A constant pointer means that the pointer in consideration will always point to the same address. Its address cannot be modified. A pointer to a constant refers to a pointer which is pointing to a symbolic constant. Using a pointer to a constant, the constant value cannot be modified; the pointer can be made to point to another location. 11

Int *const cpyr =&n; Const int kn =99; 18. Explain pointer arithmetic operations. INCREMENTING A POINTER A pointer holds the address of another variable. If a pointer variable is incremented by 1, then the pointer will point to the next memory location of its type, which is adjunct to the previous pointed address. #include<iostream.h> Main () Int i=4,*ipr; Float f=98.4,*fpr; Char c= a,*cpr; /*INITIALIZE*/ Ipr=&I; Fpr =&f; Cpr =&c; cout<<"\n the value of I is"<<*ipr); cout<<"\n the value of f is "<< *fpr); cout<<"the value of c is "<<cpr); cout<<"\n ACTUAL ADDRESS STORED IN POINTER"; cout<<"\n ipr points to "<< ipr); cout<<"\n fpr points to "<< fpr); cout<<"\n cpr points to"<< cpr); Ipr++; 12

Fpr++; Cpr++; cout<<"address STORED IN POINTER AFTER POINTER INCREMENTED"; cout<<"\n ipr points to"<< ipr; cout<<"\n fpr points to "<< fpr; cout<<"\n cpr points to "<< cpr; Getch (); DECREMENTING THE POINTER A pointer variable if incremented points to the next memory location. Likewise, if a pointer variable is decremented, it points to the previous memory location. #include<iostream.h> Main () Int i=4,*ipr; Float f=98.4,*fpr; Char c= a,*cpr; /*INITIALIZE*/ Ipr=&I; Fpr =&f; Cpr =&c; cout<<"\n the value of I is "<<*ipr; cout<<"\n the value of f is "<< *fpr; cout<<"the value of c is"<<*cpr); cout<<"\n ACTUAL ADDRESS STORED IN POINTER"; cout<<"\n ipr points to"<< ipr; 13

cout<<"\n fpr points to "<< fpr); cout<<"\n cpr points to"<< cpr); Ipr--; Fpr--; Cpr--; cout<<"address STORED IN POINTER AFTER POINTER INCREMENTED"; cout<<"\n ipr points to "<<ipr; cout<<"\n fpr points to "<< fpr; cout<<"\n cpr points to "<< cpr; Getch (); POINTERS ADDITION An integer value can be added to a pointer variable which points to an integer, and then the value of the pointer variable will be incremented by 14. Since the memory requirement for an integer is 2. Hence, for 7 integers a total of 14 bytes is required. Real value should not be applied while performing pointer addition. Int *ipr, i=5; (valid) Ipr = &I; (valid) Ipr =ipr + 1.5; (invalid) POINTERS SUBTRACTION Pointers subtraction can be used to shift the pointer to point to the previous location. The following operations should not be performed. If used, the following error messages will be generated. (i) Addition of a pointer with a real value - illegal use of floating point (ii) Addition of two pointers-invalid pointer addition (iii) Multiplying a pointer with a value illegal use of pointer. (iv) Dividing a pointer with a value illegal use of pointer 19. Differentiate static and dynamic memory allocation. 14

Static memory allocation: The compiler allocates the required memory space for a declared variable. By using the address of operator, the reserved address is obtained and this address may be assigned to a pointer variable. Since most of the declared variables have a static memory, this way of assigning pointer value to a pointer variable is known as static memory allocation. Memory is assigned during compilation time. Static memory allocation is before run time, but the values of variables may be changed at run time. Static memory allocation saves running time, but can't be possible in all cases. Dynamic memory allocation: It uses functions such as malloc( ) or calloc( ) to get memory dynamically. If these functions are used to get memory dynamically and the values returned by these functions are assigned to pointer variables, such assignments are known as dynamic memory allocation. Memory is assigned during run time. Dynamic memory allocation is at runtime. Dynamic memory allocation stores its memory on heap, and the static memory allocation stores its data in the "data segment" of the memory. 20. How do you declare and initialize pointers? C provides the following two special pointer operators to manipulate the data item directly from the memory location. The address operation (&) The indirection operator (*) Int a=5; The above variable instructs the C compiler to reserve a memory location to hold an integer value because in the declaration we have used the type of the variable, as int. This memory location is referred by the variable name a and finally, the value 5 will be stored in the memory location. In simpler terms, we say that 5 is assigned to a. we know that it is a number and now the question is how to find the address of the memory location. The answer is very simple. We can find the address by using the address of operators (&) as illustration in the following example. Main () Int a=5; cout<<"the value of a<< a; cout<<"the address of a"<<&a); Getch (); 15

If we run the program, the output would be as follow: The value of a=5. The address of a =5466. The first output statement prints the value stored in the memory location referred by the variable name a whereas in the second output statement we have included & values precede the variable name a. This operation instructs the compiler to print the address of the variable name a. The address operator (&) acts on ordinary variables or single array elements associated with a unique address and not on arithmetic operators. The indirection operator is also called as the value at address operator. This operator returns the value stored at the specified address where the indirection (*) operator operates only on operands called pointer variable. POINTER VARIABLE DECLARTION POINTER VARIABLE A pointer variable like any other variable should be declared before using it where the pointer variable is declared as follows:- DATA TYPE * POINTER-VARIABLE-NAME The data type refers to the data type of the variable that the pointer will point to. Note: The pointer variable name should be preceded by an asterisk (*). Int * ptr-to-int; INITIALIZATION OF POINTER It is advisable to initialize pointer variable as soon as they are declared. Since pointer variable stores addresses, they can address any portion of the memory. Example: - int a, *ptr-to-int; The first statement instructs the compiler to reserve a space for the variable a in the memory that holds an integer value. Next, another memory space for the pointer variable ptr-to-int, that will hold the address of an integer variable, is declared. Main () int a=5; int *pr; 16

Clrscr (); Pr = &a; cout<<"address of a "<< &a); cout<<"address of a "<< pr); cout<<"value of pr "<< pr); cout<<"value of a = "<< a); cout<<"value of a = "<< *(&a) ; cout<<"value of a = "<< *pr); cout<<"address of pr = "<< &pr); Getch (); OUTPUT IS:- Address of a = f6c Address of a = f6c Value of pr = f6c Value of a = 5 Value of a = 5 Value of a = 5 Address of pr = f6c 17