TCS c datastructure interview Questions questions
1)How do you write a function that can reverse a linked-list? void reverselist(void)
{
if(head==0)
return;
if(head->next==0)
return;
if(head->next==tail)
{
head->next = 0;
tail->next = head;
}
else
{
node* pre = head;
node* cur = head->next;
node* curnext = cur->next;
head->next = 0;
cur-> next = head;
for(; curnext!=0; )
{
cur->next = pre;
pre = cur;
cur = curnext;
curnext = curnext->next;
}
curnext->next = cur;
}
}
#include <stdio.h>
main()
{
typedef union
{
int a;
char b[10];
float c;
}
Union;
Union x,y = {100};
x.a = 50;
strcpy(x.b,\"hello\");
x.c = 21.50;
printf(\"Union x : %d %s %f \n\",x.a,x.b,x.c );
printf(\"Union y :%d %s%f \n\",y.a,y.b,y.c);
}
Given inputs X, Y, Z and operations | and & (meaning bitwise OR and AND, respectively)
What is output equal to in
output = (X & Y) | (X & Z) | (Y & Z)
3)What is the difference between char a[] = “string”; and char *p = “string”; ?
Answer1
a[] = “string”;
char *p = “string”;
The difference is this:
p is pointing to a constant string, you can never safely say
p[3]=’x';
however you can always say a[3]=’x';
char a[]=”string”; - character array initialization.
char *p=”string” ; - non-const pointer to a const-string.( this is permitted only in the case of char pointer in C++ to preserve backward compatibility with C.)
Answer2
a[] = “string”;
char *p = “string”;
a[] will have 7 bytes. However, p is only 4 bytes. P is pointing to an adress is either BSS or the data section (depending on which compiler — GNU for the former and CC for the latter).
Answer3
char a[] = “string”;
char *p = “string”;
for char a[]…….using the array notation 7 bytes of storage in the static memory block are taken up, one for each character and one for the terminating nul character.
But, in the pointer notation char *p………….the same 7 bytes required, plus N bytes to store the pointer variable “p” (where N depends on the system but is usually a minimum of 2 bytes and can be 4 or more)……
4)How do I declare an array of N pointers to functions returning pointers to functions returning pointers to characters?
Answer1
If you want the code to be even slightly readable, you will use typedefs.
typedef char* (*functiontype_one)(void);
typedef functiontype_one (*functiontype_two)(void);
functiontype_two myarray[N]; //assuming N is a const integral
Answer2
char* (* (*a[N])())()
Here a is that array. And according to question no function will not take any parameter value.
5)Will the following program execute?
void main()
{
void *vptr = (void *) malloc(sizeof(void));
vptr++;
}
Answer1
It will throw an error, as arithmetic operations cannot be performed on void pointers.
Answer2
It will not build as sizeof cannot be applied to void* ( error “Unknown size” )
Answer3
How can it execute if it won’t even compile? It needs to be int main, not void main. Also, cannot increment a void *.
Answer4
According to gcc compiler it won’t show any error, simply it executes. but in general we can’t do arthematic operation on void, and gives size of void as 1
Answer5
The program compiles in GNU C while giving a warning for “void main”. The program runs without a crash. sizeof(void) is “1? hence when vptr++, the address is incremented by 1.
Answer6
Regarding arguments about GCC, be aware that this is a C++ question, not C. So gcc will compile and execute, g++ cannot. g++ complains that the return type cannot be void and the argument of sizeof() cannot be void. It also reports that ISO C++ forbids incrementing a pointer of type ‘void*’.
Answer7
in C++
voidp.c: In function `int main()’:
voidp.c:4: error: invalid application of `sizeof’ to a void type
voidp.c:4: error: `malloc’ undeclared (first use this function)
voidp.c:4: error: (Each undeclared identifier is reported only once for each function it appears in.)
voidp.c:6: error: ISO C++ forbids incrementing a pointer of type `void*’
But in c, it work without problems
6)void main()
{
char *cptr = 0?2000;
long *lptr = 0?2000;
cptr++;
lptr++;
printf(” %x %x”, cptr, lptr);
}
Will it execute or not?
Answer1
For Q2: As above, won’t compile because main must return int. Also, 0×2000 cannot be implicitly converted to a pointer (I assume you meant 0×2000 and not 0?2000.)
Answer2
Not Excute.
Compile with VC7 results following errors:
error C2440: ‘initializing’ : cannot convert from ‘int’ to ‘char *’
error C2440: ‘initializing’ : cannot convert from ‘int’ to ‘long *’
Not Excute if it is C++, but Excute in C.
The printout:
2001 2004
Answer3
In C++
[$]> g++ point.c
point.c: In function `int main()’:
point.c:4: error: invalid conversion from `int’ to `char*’
point.c:5: error: invalid conversion from `int’ to `long int*’
in C
———————————–
[$] etc > gcc point.c
point.c: In function `main’:
point.c:4: warning: initialization makes pointer from integer without a cast
point.c:5: warning: initialization makes pointer from integer without a cast
[$] etc > ./a.exe
2001 2004
7)Write a fucntion that will reverse a string.
char *strrev(char *s)
{
int i = 0, len = strlen(s);
char *str;
if ((str = (char *)malloc(len+1)) == NULL)
/*cannot allocate memory */
err_num = 2;
return (str);
}
while(len)
str[i++]=s[–len];
str[i] = NULL;
return (str);
}
8)What is alloca()
Ans : It allocates and frees memory after use/after getting out of scope
Ans : It allocates and frees memory after use/after getting out of scope
9)What will the following program do?
void main(){
int i;
char a[]="String";
char *p="New Sring";
char *Temp;
Temp=a;
a=malloc(strlen(p) + 1);
strcpy(a,p); //Line number:9//
p = malloc(strlen(Temp) + 1);
strcpy(p,Temp);
printf("(%s, %s)",a,p);
free(p);
free(a);
} //Line number 15//
a) Swap contents of p & a and print:(New string, string)
b) Generate compilation error in line number 8
c) Generate compilation error in line number 5
d) Generate compilation error in line number 7
e) Generate compilation error in line number 1
Ans. (b)
void main(){
int i;
char a[]="String";
char *p="New Sring";
char *Temp;
Temp=a;
a=malloc(strlen(p) + 1);
strcpy(a,p); //Line number:9//
p = malloc(strlen(Temp) + 1);
strcpy(p,Temp);
printf("(%s, %s)",a,p);
free(p);
free(a);
} //Line number 15//
a) Swap contents of p & a and print:(New string, string)
b) Generate compilation error in line number 8
c) Generate compilation error in line number 5
d) Generate compilation error in line number 7
e) Generate compilation error in line number 1
Ans. (b)
10)Find the output of the following program
class Sample
{
public:
int *ptr;
Sample(int i)
{
ptr = new int(i);
}
~Sample()
{
delete ptr;
}
void PrintVal()
{
cout << "The value is " << *ptr;
}
};
void SomeFunc(Sample x)
{
cout << "Say i am in someFunc " << endl;
}
int main()
{
Sample s1= 10;
SomeFunc(s1);
s1.PrintVal();
}
Answer:
Say i am in someFunc
Null pointer assignment(Run-time error)
Explanation:
As the object is passed by value to SomeFunc the destructor of the object is called when the control returns from the function. So when PrintVal is called it meets up with ptr that has been freed.The solution is to pass the Sample object by reference to SomeFunc:
void SomeFunc(Sample &x)
{
cout << "Say i am in someFunc " << endl;
}
because when we pass objects by refernece that object is not destroyed. while returning from the function.
11).Which is the parameter that is added to every non-static member function when it is called?
Answer:
‘this’ pointer
12).Find the output of the following program
class base
{
public:
int bval;
base(){ bval=0;}
};
class deri:public base
{
public:
int dval;
deri(){ dval=1;}
};
void SomeFunc(base *arr,int size)
{
for(int i=0; i cout<bval;
cout<}
int main()
{
base BaseArr[5];
SomeFunc(BaseArr,5);
deri DeriArr[5];
SomeFunc(DeriArr,5);
}
Answer:
00000
01010
56.Find the output of the following program
class base
{
public:
void baseFun(){ cout<<"from base"< };
class deri:public base
{
public:
void baseFun(){ cout<< "from derived"< };
void SomeFunc(base *baseObj)
{
baseObj->baseFun();
}
int main()
{
base baseObject;
SomeFunc(&baseObject);
deri deriObject;
SomeFunc(&deriObject);
}
Answer:
from base
from base
Explanation:
As we have seen in the previous case, SomeFunc expects a pointer to a base class. Since a pointer to a derived class object is passed, it treats the argument only as a base class pointer and the corresponding base function is called.
57.Find the output of the following program
class base
{
public:
virtual void baseFun(){ cout<<"from base"< };
class deri:public base
{
public:
void baseFun(){ cout<< "from derived"< };
void SomeFunc(base *baseObj)
{
baseObj->baseFun();
}
int main()
{
base baseObject;
SomeFunc(&baseObject);
deri deriObject;
SomeFunc(&deriObject);
}
Answer:
from base
from derived
Explanation:
Remember that baseFunc is a virtual function. That means that it supports run-time polymorphism. So the function corresponding to the derived class object is called.
58.Find the output of the following program
void main()
{
int a, *pa, &ra;
pa = &a;
ra = a;
cout <<"a="<}
Answer :
Compiler Error: 'ra',reference must be initialized
Explanation :
Pointers are different from references. One of the main
differences is that the pointers can be both initialized and assigned,
whereas references can only be initialized. So this code issues an error.
59.Find the output of the following program
const int size = 5;
void print(int *ptr)
{
cout<}
void print(int ptr[size])
{
cout<}
void main()
{
int a[size] = {1,2,3,4,5};
int *b = new int(size);
print(a);
print(b);
}
Answer:
Compiler Error : function 'void print(int *)' already has a body
Explanation:
Arrays cannot be passed to functions, only pointers (for arrays, base addresses)
can be passed. So the arguments int *ptr and int prt[size] have no difference
as function arguments. In other words, both the functoins have the same signature and
so cannot be overloaded.
60.Find the output of the following program
class some{
public:
~some()
{
cout<<"some's destructor"< }
};
void main()
{
some s;
s.~some();
}
Answer:
some's destructor
some's destructor
Explanation:
Destructors can be called explicitly. Here 's.~some()' explicitly calls the
destructor of 's'. When main() returns, destructor of s is called again,
hence the result.
61.Find the output of the following program
#include
class fig2d
{
int dim1;
int dim2;
public:
fig2d() { dim1=5; dim2=6;}
virtual void operator<<(ostream & rhs);
};
void fig2d::operator<<(ostream &rhs)
{
rhs <dim1<<" "<dim2<<" ";
}
/*class fig3d : public fig2d
{
int dim3;
public:
fig3d() { dim3=7;}
virtual void operator<<(ostream &rhs);
};
void fig3d::operator<<(ostream &rhs)
{
fig2d::operator <<(rhs);
rhs<dim3;
}
*/
void main()
{
fig2d obj1;
// fig3d obj2;
obj1 << cout;
// obj2 << cout;
}
Answer :
5 6
Explanation:
In this program, the << operator is overloaded with ostream as argument.
This enables the 'cout' to be present at the right-hand-side. Normally, 'cout'
is implemented as global function, but it doesn't mean that 'cout' is not possible
to be overloaded as member function.
Overloading << as virtual member function becomes handy when the class in which
it is overloaded is inherited, and this becomes available to be overrided. This is as opposed
to global friend functions, where friend's are not inherited.
62.Find the output of the following program
class opOverload{
public:
bool operator==(opOverload temp);
};
bool opOverload::operator==(opOverload temp){
if(*this == temp ){
cout<<"The both are same objects\n";
return true;
}
else{
cout<<"The both are different\n";
return false;
}
}
void main(){
opOverload a1, a2;
a1= =a2;
}
Answer :
Runtime Error: Stack Overflow
Explanation :
Just like normal functions, operator functions can be called recursively. This program just illustrates that point, by calling the operator == function recursively, leading to an infinite loop.
63.Find the output of the following program
class complex{
double re;
double im;
public:
complex() : re(1),im(0.5) {}
bool operator==(complex &rhs);
operator int(){}
};
bool complex::operator == (complex &rhs){
if((this->re == rhs.re) && (this->im == rhs.im))
return true;
else
return false;
}
int main(){
complex c1;
cout<< c1;
}
Answer : Garbage value
Explanation:
The programmer wishes to print the complex object using output
re-direction operator, which he has not defined for his lass. But the compiler instead of giving an error sees the conversion function
and converts the user defined object to standard object and prints
some garbage value.
64.Find the output of the following program
class complex{
double re;
double im;
public:
complex() : re(0),im(0) {}
complex(double n) { re=n,im=n;};
complex(int m,int n) { re=m,im=n;}
void print() { cout<};
void main(){
complex c3;
double i=5;
c3 = i;
c3.print();
}
Answer:
5,5
Explanation:
Though no operator= function taking complex, double is defined, the double on the rhs is converted into a temporary object using the single argument constructor taking double and assigned to the lvalue.
65.Find the output of the following program
void main()
{
int a, *pa, &ra;
pa = &a;
ra = a;
cout <<"a="<}
}
Answer :
Compiler Error: 'ra',reference must be initialized
Explanation :
Pointers are different from references. One of the main
differences is that the pointers can be both initialized and assigned, whereas references can only be initialized. So this code issues an error
click the Below link download this file |
---|
If you enjoyed this post and wish to be informed whenever a new post is published, then make sure you subscribe to my regular Email Updates. Subscribe Now!
2 comments:
I have read your article, it is very informative and helpful for me.I admire the valuable information you offer in your articles. Thanks for posting it..
social bookmarking service
11. Hi There,
Grazie! Grazie! Grazie! Your blog is indeed quite interesting around C++ Interview Questions and Answers I agree with you on lot of points!
A subset of a natural language contains these sentences:
1) Triangle ABC.
2) Line Segment AB.
3) Angle A.
In this set, names of triangles are formed by putting three letters together,
all drawn from the alphabet {A,B,C,D,E}. Line segment names are defined by
putting two letters together from the previous alphabet. And angle names are
(suprise!) given by any letter in that alphabet.
Great effort, I wish I saw it earlier. Would have saved my day :)
Thank you,
Preethi
Have any question? Feel Free To Post Below: