1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Interview question.

Discussion in 'C++' started by SATYAN JANA, Sep 28, 2005.

  1. SATYAN JANA

    SATYAN JANA New Member

    Joined:
    Jul 31, 2004
    Messages:
    7
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Programming
    Location:
    Kolkata
    A good question usually asked at interviews,-

    /**************************/
    int * func(int, int);
    void main()
    {
    int *ptr = func(2,3);
    printf("\nHello World!\n");
    printf("\n%d\n",*ptr);
    }
    int * func(int i, int j)
    {
    int k = i + j;
    return &k;
    }
    /**************************/
    What will be the output of the above program?
    Scroll down for answer.
































    Here is the output,-
    Hello World!
    Garbage Value

    Note that Garbage Value will be printed here instead of 5. This is because once the control returns from func() to the main(), the address of local variable 'k' is free. So the contents of this address can be modified by anybody else.
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,283
    Likes Received:
    364
    Trophy Points:
    83
    I will add one more here
    Code:
    void AllocateMem(int *p)
    {
      p = (int*)malloc(sizeof(int));
      *p = 6;
      return;
    }
    
    void main()
    {
      int *a;
      AllocateMem(&a); 
      printf("[%d]",*a);
    }
    
    Gives an exception. I want the function to allocate the memory and want that to use in main. How?
    Scroll down for an answer




















    Code:
    void AllocateMemory(int **p)
    {
      *p = (int*)malloc(sizeof(int));
      **p = 6;
      return;
    }
    
    void main()
    {
      int *a;
      AllocateMemory(&a);
      printf("[%d]",*a);
    }
     
  3. coderzone

    coderzone Super Moderator

    Joined:
    Jul 25, 2004
    Messages:
    734
    Likes Received:
    37
    Trophy Points:
    0
    I will add one
    Code:
    class A
    {
    private:
      int a;
    public:
      void func(void);
    };
    
    class B
    {
    private:
      int a;
    public:
      virtual void func(void);
    };
    
    int main()
    {
      A a;
      B b;
      cout<<sizeof(a)<<"  "<<sizeof(b)<<endl;
    }
    
    What will be the output of the above program and why?
    Scroll down for an answer




























    2 4 because there is a Pointer to the virtual table to resolve the dynamic binding of the virtual function.
     
  4. go4expert

    go4expert Moderator

    Joined:
    Aug 3, 2004
    Messages:
    306
    Likes Received:
    7
    Trophy Points:
    0

Share This Page