C++ interview questions and answers

  1. What is the most efficient way to reverse a linklist?
  2. How to sort & search a single linklist?
  3. Which is more convenient - single or double-linked linklist? Discuss the trade-offs? What about XOR-linked linklist?
  4. How does indexing work?
  5. char s[10];
    s=”Hello”;
    printf(s);

    What will be the output? Is there any error with this code?
  6. What is the difference between
    char s[]=”Hello”;
    char *s=”Hello”;

    Please give a clear idea on this?
  7. Why do we pass a reference for copy constructors? If it does shallow copy for pass by value (user defined object), how will it do the deep copy?
  8. What is the difference between shallow copy & deep copy?
  9. What is the difference between strcpy and memcpy? What rule should we follow when choosing between these two?
  10. If we declare two variable and two applications are using the same variable, then what will its value be, will it be the same?
This entry was posted in C++. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

19 Comments on C++ interview questions and answers

  1. Hemanth
    Posted 12/12/2007 at 8:15 am | Permalink

    5. The declaration char s[10] implies that ’s’ has a fixed adrress in memory i.e it is a constant pointer. The right hand operand produces a pointer to a memory location that holds the character string “Hello”. Thus, it is clear from this code that there is an attempt to modify a constant pointer by assigning it an address. This will give compilation error.

    6.
    char s[]=”Hello”;
    char *s=”Hello”;
    The only difference between the two statements is that the former is declaring a “constant pointer to a variable string” while the latter is declaring a “variable pointer to constant string”.

    i) char s[] = “Hello”; ’s’ is constant pointer

    we can change its contents like
    s[0] = ‘b’, s[1]=’y', s[2] = ‘e’ ..so on

    ii) char *s = “Hello”; ’s’ is a variable pointer.
    we cannot change its contents like above. Doing so produces run time errors.

  2. Ashutosh Agrawal
    Posted 1/5/2008 at 2:26 am | Permalink

    #1. The most efficient way to reverse a linked list is thorough recursion.
    example:

    void rev(struct node *list)
    {
    if (list->next==NULL)return;
    rev(list->next);
    printf(”%d”,list->info);
    }

    #2. Searching a linked list is a very easy concept, just traverse each node till the next node pointer value is NULL and see if the value in the node matched the one we have to search or not.

    Sorting a linked list can be a bit complicated though, we can use bubble sort technique and swap values using functions.

    #3. A singly linked list can be very easy to handle but it can be traversed in one direction only whereas a douly linked list can be traversed in both reverse and forward direction. Thus a doubly linked list is advantageous over singly linked list.

    #5. The error here is that the assignment used here that is s=”hello”; is not correct. either we will have to change the declaration to char *s; or we will have to use the function strcpy(s,”hello”); to do such assignment.

  3. Posted 1/12/2008 at 4:34 pm | Permalink

    “ii) char *s = “Hello”; ’s’ is a variable pointer.
    we cannot change its contents like above. Doing so produces run time errors”

    You can certainly change anything you want cause you have a pointer to a memory buffer. Since you know its chars you can directly access the memory address of s….

    char *pString = NULL;
    printf(”%d\n”,&pString);
    *((&pString)) = “Some silly string\n”;
    printf(pString);
    printf(”%d\n”,&pString);

    char *pStringT = “Hello\n”;
    printf(”%d\n”,&pStringT);
    *((&pStringT)) = “Some silly string\n”;
    printf(pStringT);
    printf(”%d\n”,&pStringT);

  4. M Imtiaz Sharif
    Posted 1/18/2008 at 5:51 am | Permalink

    Hello,

    1) The best way to reverse the link list is through recursion, code is as follow:

    void reverseLinkList (Node *node)
    {
    if(node -> next == null)
    return;

    reverseLinkList (node -> next);

    node -> next -> next = node;
    }

    2) Searching in the link list is simple, just traverse its node one by one and compare each node value with ur required value,
    You can use loop for it or the recursion

    As far sorting is required, i think applying bubble sort on the list is much convenient, cpde is as follow:

    void sortLinkList (Node *headNode)
    {
    if(headNode == null)
    return;

    bool sortingComplete = false;

    for(Node *temp1 = headNode; temp1 != null; )
    {
    sortingComplete = true;

    for(Node *temp2 = temp1 -> next; temp2 != null;)
    {
    if(temp1 -> value > temp2 -> value)
    {

    sortingComplete = false;
    }

    temp1 = headNode;
    temp2 = temp1 -> next;
    }

    if(sortingComplete)
    break;

    {
    }

    (i havn’t run this code but i m sure that it will work exact fine)

    3) Single Link list is just the one way flow of the nodes while in double link list u can traverse forward or backward.
    If u r good with pointers and their trade offs than i sugguest use double link list as handling data with them is much easier.
    No idea abt XOR link list

    5) The output will be only ‘H’, as in the char[], the name ’s’ only points to the first byte of the array.

    6) First one is a const pointer to a const memory
    Where second one is dynamic pointer to a const memory

    8) User has created its own class now two ways to explain this….
    – if there is no pointer use as an attribute of the class, than both deep copy & shallow copy are the same

    – but if their is any pointer use as an attribute than behaviour of both will be diff….shallow copy will only create new reference and will
    refer it to the same memory location where the previous one is pointing, means single memory location poited by two pointers…..where deep
    copy will also allocate new memory for the new reference and then will copy the contents of the first memory location to the second one.

    10) it depends on the scope of the variable , if its scope is of application level than both will get different copies of the variable…but if it is a system variable or scope not restricted to a single application than both will recieve same value/copy.

  5. pavan
    Posted 1/25/2008 at 11:36 am | Permalink

    7. whenever you do a pass by value copy constructor is called. So if u pass by value for a copy constructor it again invokes itself and it will be a continuos process with getting an un ending loop. so copy constructor is always pass by refrence. deep cpy is done using copy constructor

  6. Chris Taylor
    Posted 1/25/2008 at 5:42 pm | Permalink

    1) Not sure that recursion is the best answer … creates a lot of extra space on the call stack.
    void reverseLinkList (Node *node)
    {
    Node* C = NULL;
    Node* B = node;
    Node* A = node;

    //handle the case where there’s only 1 element
    if(B->next==NULL)
    return;

    while(B!=NULL)
    {
    A=A->next;
    B->next = C;

    C=B;
    B=A;
    }
    //reset node so it’s the new head
    node = C;
    }

    thoughts, suggestions?

    Respectfully,
    Christopher Taylor

  7. Saurabh Gupta
    Posted 3/3/2008 at 8:24 am | Permalink

    Agreed with Christopher; recursion may not be best choice for a big list. However, I found the implementations given using recursion in earlier answers were not correct. And this bugged me and I wrote this one (suggestions?):

    void RevertRecursively(Node* n, Node* &reversedList)
    {
    if(NULL == n->pNext->pNext)
    {
    n->pNext->pNext = n;
    reversedList = n->pNext;
    return;
    }
    else
    {
    RevertRecursively(n->pNext, reversedList);
    n->pNext->pNext = n;
    }
    }

    void Revert(Node* &n)
    {
    if(NULL == n || NULL == n->pNext)
    return; //none or single element do nothing

    Node * reversedList = NULL;
    RevertRecursively(n, reversedList);
    n->pNext = NULL;
    n = reversedList;
    }

    void Print(Node* n)
    {
    cout<<”Printing…”<<endl;
    Node *t = n;
    while(t)
    {
    cout<Val<pNext;
    }
    cout<<”Done”<<endl;
    }

    void main()
    {
    //creating a linked list
    Node n5(5);
    Node n4(4, &n5);
    Node n3(3, &n4);
    Node n2(2, &n3);
    Node n1(1, &n2);

    //printing it
    Node *n = &n1;
    Print(n);
    //reverting and printing it
    Revert(n);
    Print(n);
    }

  8. Saurabh Gupta
    Posted 3/3/2008 at 8:25 am | Permalink

    I missed the obvious :)

    class Node
    {
    public:
    Node* pNext;
    int Val;
    Node(int i, Node* pN = NULL)
    {
    pNext = pN;
    Val = i;
    }
    };

  9. karthik.r
    Posted 3/7/2008 at 1:37 am | Permalink

    1>efficient way geeting the output is nothing but
    cosidering the two facts
    *time,*space
    if we prefer recursion,stack consumption goes very high(repeted function call);
    time spent in calling and returning; 

  10. Balwinder
    Posted 3/15/2008 at 12:56 pm | Permalink

    8. In shallow copy, we have one memory location shared by two or more variables. In deep copy, each copy of a variable will have its own memory different from other, though the contents will be same. Confussion!! Let me clearify with an example.
    void makecopy(userdefined* obj)
    {
    userdefined* newCopy = obj//Shallow copy. //Points to same memory as the argument
    }
    //Deep copy……allocates memory and copy the contents
    void makeDeepcopy(userdefined* obj)
    {
    userdefined* deepcopy = new userdefined();
    deepcopy->data = obj->data;
    }

  11. Posted 3/16/2008 at 1:54 pm | Permalink

    10> This is a typical question about thread synchronization. For example, let the two variables be a and b, and the operations be a++ and b++, which happen in both threads.
    a++ can be viewed as:
    read a;
    increment a;
    write a;
    Thus, while thread 1 has read and incremented a, if thread 2 gets scheduled and writes a back, we have a problem because 1’s values is now stale.

  12. Michael Cornell
    Posted 3/18/2008 at 12:01 am | Permalink

    1>Fastest time is O(n). Recursion is the easiest implementation :

    List * pHead;

    List* Inverse(List* p) {
          if (p->next == NULL) {// so this is the new Head
                pHead = p; //or st along that line.
                return p;
          }
          (Inverse(p->next))->next=p;
          return p;
    }
    int main () {
        // initialize a sample list.
        List *pBottom = Inverse(pHead);
        pBottom->next=NULL;
        pHead->browse();
    }

  13. HerbertYu
    Posted 3/25/2008 at 1:48 am | Permalink

    #1 What is the most efficient way to reverse a linklist?
    // Just one loop to reverse itstruLinkedList *p1, *p2, *p3;p1 = pHeader;p2 = p1->next; // pHeader != NULLp1->next = NULL; // change header to tailwhile(p2->next) {p3 = p2->next;p2->next = p1;p1 = p2;p2 = p3;}p2->next = p1;pHeader = p2; // New header

  14. Manish
    Posted 3/25/2008 at 6:09 pm | Permalink

    I agree with Herbert. The more important thing to call out is that recursion is not the most efficient way. use too much of it it bloat your runtime.

  15. sowmya
    Posted 4/14/2008 at 10:25 am | Permalink

    ques.no.8:::A shallow copy of an object copies all of the member field values. This works well if the fields are values, but may not be what you want for fields that point to dynamically allocated memory. The pointer will be copied. but the memory it points to will not be copied — the field in both the original object and the copy will then point to the same dynamically allocated memory, which is not usually what you want. The default copy constructor and assignment operator make shallow copies.

    A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. To make a deep copy, you must write a copy constructor and overload the assignment operator, otherwise the copy will point to the original, with disasterous consequences.

  16. rakesh
    Posted 5/6/2008 at 12:08 pm | Permalink

    Question 1:
    List *revlist(List *HeadNode)
    {
    List *p = HeadNode;
    if(p == NULL || p->next == NULL )
    return p;
    HeadNode = revlist(p->next);
    p->next->next = p;
    p->next = NULL;
    return HeadNode;
    }

  17. goutam
    Posted 5/30/2008 at 12:40 am | Permalink

    5..
    there will be no output b’cause

    s is declared as a character constant so it doesnot allow to assign some variable name to it

    it gives compile time error

  18. Chi Huynh
    Posted 6/9/2008 at 2:36 pm | Permalink

    2. How to sort & search a single linklist?
    Answer: Most of C++ compilers come with STL. Use the functions provided by the STL to do sort and search rather than re-invent the wheel.

  19. kay
    Posted 11/19/2008 at 8:40 pm | Permalink

    6. the first case pass string to an array, while the second case pass the first address of the string to the pointer

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*