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