Languages [3i Infotech Placement]: Sample Questions 190 - 191 of 546
Glide to success with Doorsteptutor material for competitive exams : get questions, notes, tests, video lectures and more- for all subjects of your exam.
Question 190
Explanation
- In C, Malloc allocates new memory space of size “newsize” to the pointer variable “ptr” and returns a pointer to the first byte of the new memory block.
- The new size may be smaller or large than original size, it returns a NULL pointer and the original block is freed
- If the function is unsuccessful in allocating additional space
- Subsequently memcpy (memory copy) function can be used to copy the contents from old location to new location.
- C ++ memory allocation using “new” is allocated below.
Program in C ++ (Using New to Allocated Memory) :
int main()
{
string⚹name =NULL;
name =new string[1];
name[0] ="Mike";
cout ≪ name[0] ≪ endl;
delete [] name;
name =new string[3];
name[0] ="Mike";
name[1] ="Steve";
name[2] ="Dave";
cout ≪ name[0] ≪ endl;
cout ≪ name[1] ≪ endl;
cout ≪ name[2] ≪ endl;
delete [] name;
while (_kbhit() == 0);
return 0;
}
Question 191
Explanation
- A class used to traverse through the objects maintained by a container class. There are five categories of iterators:
- input iterators,
- output iterators,
- forward iterators,
- bidirectional iterators,
- random access.
- An iterator gives access to the contents of a container object without violating encapsulation.
- Access is granted on a one-at-a-time basis in order.
- The order can be storage order (as in lists and queues) or some arbitrary order (as in array indices) or follow some ordering relation (as in an ordered binary tree) .
- The iterator is a construct, when called, yields either the next element in the container, or some value denoting the fact that there are no more elements to examine.
- Iterators hide the details of access to and update of the elements of a container class.
- The simplest and safest iterators are those that permit read-only access to the contents of a container class.
- The following code fragment shows how an iterator might appear in code: cont_iter:= new cont_iterator () ; x:= cont_iter. next () ; while x/ = none do … s (x) ; … x:= cont_iter. next () ; end;
- In this example, cont_iter is the name of the iterator.
- It is created on the first line by instantiation of cont_iterator class, an iterator class defined to iterate over some container class, cont. Succesive elements from the container are carried to x.
- The loop terminates when x is bound to some empty value (here, none) . In the middle of the loop, there is s (x) an operation on x, the current element from the container.
- The next element of the container is obtained at the bottom of the loop.