Sunday, March 21, 2010

Help for C

1.    what is the output of the program?

#include
main()
{
struct s1 {int i; };
struct s2 {int i; };
struct s1 st1;
struct s2 st2;
st1.i =5;
st2 = st1;
printf(" %d " , st2.i);
}

ans: nothing (error)
expl: diff struct variables should not assigned using "=" operator.


2.    what is the output of the program?

main()
{
struct emp{
char emp[];
int empno;
float sal;
};
struct emp member = { "TIGER"};
printf(" %d %f", member.empno,member.sal);

ans: error. In struct variable emp[], we have to give array size.
If array size given
ans is 0, 0.00


3.    if ptr is defined as

int *ptr[][100];
which of the following correctly allocates memory for ptr?

ans: ptr = (int *)(malloc(100* sizeof(int));

4.    What is the output for the program given below

typedef enum grade{GOOD,BAD,WORST,}BAD;
main()
{
BAD g1;
g1=1;
printf("%d",g1);
}


4. Give the output for the following program.

#define STYLE1 char
main()
{
typedef char STYLE2;
STYLE1 x;
STYLE2 y;
clrscr();
x=255;
y=255;
printf("%d %d\n",x,y);
}


5. main()
{
while (strcmp(“some”,”some\0”))
printf(“Strings are not equal\n”);
}
Answer:
No output
Explanation:
Ending the string constant with \0 explicitly makes no difference. So “some” and “some\0” are equivalent. So, strcmp returns 0 (false) hence breaking out of the while loop.



6. main()
{
char str1[] = {‘s’,’o’,’m’,’e’};
char str2[] = {‘s’,’o’,’m’,’e’,’\0’};
while (strcmp(str1,str2))
printf(“Strings are not equal\n”);
}
Answer:
“Strings are not equal”
“Strings are not equal”
….
Explanation:
If a string constant is initialized explicitly with characters, ‘\0’ is not appended automatically to the string. Since str1 doesn’t have null termination, it treats whatever the values that are in the following positions as part of the string until it randomly reaches a ‘\0’. So str1 and str2 are not the same, hence the result.

7.    {
int *mptr, *cptr;
mptr = (int*)malloc(sizeof(int));
printf(“%d”,*mptr);
int *cptr = (int*)calloc(sizeof(int),1);
printf(“%d”,*cptr);
}
Answer:
garbage-value 0
Explanation:
The memory space allocated by malloc is uninitialized, whereas calloc returns the allocated memory space initialized to zeros.


8.    {
char a[]="\0";
if(printf("%s\n",a))
printf("Ok here \n");
else
printf("Forget it\n");
}

Answer: Ok here

Explanation:
Printf will return how many characters does it print. Hence printing
a new-line character returns 1 which makes the if statement true, thus "Ok here" is printed.


9.     void main()
{
while(1){
if(printf("%d",printf("%d")))
break;
else
continue;
}

Answer:
Garbage values
Explanation:
The inner printf executes first to print some garbage value. The printf returns no of characters printed and this value also cannot be predicted. Still the outer printf prints something and so returns a non-zero value. So it encounters the break statement and comes out of the while statement.



10.    int DIM(int array[])
{
return sizeof(array)/sizeof(int );
}
main()
{
int arr[10];
printf(“The dimension of the array is %d”, DIM(arr));
}
Answer:
1
Explanation:
Arrays cannot be passed to functions as arguments and only the pointers can be passed. So the argument is equivalent to int * array (this is one of the very few places where [] and * usage are equivalent). The return statement becomes, sizeof(int *)/ sizeof(int) that happens to be equal in this case.







11.     main()
{
void swap();
int x=10,y=8;
swap(&x,&y);
printf("x=%d y=%d",x,y);
}
void swap(int *a, int *b)
{
*a ^= *b, *b ^= *a, *a ^= *b;
}
Answer:
x=10 y=8
Explanation:
Using ^ like this is a way to swap two variables without using a temporary variable and that too in a single statement.
Inside main(), void swap(); means that swap is a function that may take any number of arguments (not no arguments) and returns nothing. So this doesn’t issue a compiler error by the call swap(&x,&y); that has two arguments.


12.    #include
main()
{
char * str = "hello";
char * ptr = str;
char least = 127; 65
while(*ptr++)
least = (*ptr
printf("%d",least);
}
Answer:
0
Explanation:
After ‘ptr’ reaches the end of the string the value pointed by ‘str’ is ‘\0’. So the value of ‘str’ is less than that of ‘least’. So the value of ‘least’ finally is 0.







13. Is there any difference between the two declarations,
1. int foo(int *arr[]) and
2. int foo(int *arr[2])

Answer:
No
Explanation:
Functions can only pass pointers and not arrays. The numbers that are allowed inside the [] is just for more readability. So there is no difference between the two declarations.

14.    main
{
int i=10, j=2;
int *ip= &i, *jp = &j;
int k = *ip/*jp;
printf(“%d”,k);
}
Answer:
Compiler Error: “Unexpected end of file in comment started in line 5”.
Explanation:
The programmer intended to divide two integers, but by the “maximum munch” rule, the compiler treats the operator sequence / and * as /* which happens to be the starting of comment. To force what is intended by the programmer,
int k = *ip/ *jp;
// give space explicity separating / and *
//or
int k = *ip/(*jp);
// put braces to force the intention
will solve the problem.


15.     main()
{
char a[4]="HELL";
printf("%s",a);
}

Answer:
HELL%@!~@!@???@~~!
Explanation:
The character array has the memory just enough to hold the string “HELL” and doesn’t have enough space to store the terminating null character. So it prints the HELL correctly and continues to print garbage values till it accidentally comes across a NULL character.

16.     main()
{
extern int i;
{
 int i=20;
{
const volatile unsigned i=30; printf("%d",i);
}
printf("%d",i);
}
}
int i;


17.     char *someFun()
{
char *temp = “string constant";
return temp;
}

int main()
{
puts(someFun());
}
Answer:
string constant
Explanation:
The program suffers no problem and gives the output correctly because the character constants are stored in code/data area and not allocated in stack, so this doesn’t lead to dangling pointers.

18.    char *someFun1()
{
char temp[ ] = “string";
return temp;
}
char *someFun2()
{
char temp[ ] = {‘s’, ‘t’,’r’,’i’,’n’,’g’};
return temp;
}
int main()
{
puts(someFun1());
puts(someFun2());
}
Answer:
Garbage values.
Explanation:
Both the functions suffer from the problem of dangling pointers. In someFun1() temp is a character array and so the space for it is allocated in heap and is initialized with character string “string”. This is created dynamically as the function is called, so is also deleted dynamically on exiting the function so the string data is not available in the calling function main() leading to print some garbage values. The function someFun2() also suffers from the same problem but the problem can be easily identified in this case.

19.    main()
{
char c=-64;
int i=-32;
unsigned int u =-16;
if(c>i)
{printf("pass1,");
if(c
printf("pass2");
else
printf("Fail2");
}
else
printf("Fail1);
if(i
printf("pass2");
else
printf("Fail2")
}

20.    int i,j,k;
  i=2;
    j=4;
    k=i++>j&&2;   /*     (i++>j)&2 */
    printf("%d\n",k);
    if(++k && ++i<--j|| i++)
        j=++k;
    printf(" %d %d %d",i,-j--,k);
21.    void main()
      {
            char *st1[3]= {"Hello","World","Oracle"};
            *st1=st1[2];
            st1[1]=*st1;
            free(st1[0]);
            free(st1[1]);
            clrscr();
            printf("%s %s %s",st1,st1[1],st1[2]);    //Garbeg Oracle Oracle
  }

22.    main()
{
char c = 255;printf("%d",c);
}


OUTPUT:-1



23.     main()
{
int i,count=0;
char *p1="abcdefghij";
char *p2="alcmenfoip";

for(i=0;i<=strlen(p1);i++)     // strlen gets decremented with p++
{
if(*p1++ == *p2++)        // loop runs till i=5   
count+=5;
else
count-=3;
}

printf("count=%d\n",count);
}


24.    #define mysizeof(a) (&a+1) - &a
main()
{
float d;
printf("%d\n", mysizeof(d) );
}

note: assume sizeof float is 8 bytes

a) 8
b) 4
c) 1
d) compiler error



25.    int A=1,B=2;
if(A==B < printf("Hello "))
printf("world\n");
else
printf("Bangalore\n");

What is the o/p?

a>    world
b>    Hello bangalore
c>    bangalore
d>    Hello world.



26.    register int a,b;            //ERROR
main()
{
        for(a=0 ; a<5 ; a++)
        b++;
}



27.    main()
{
for( printf("a") ; printf("b") ; printf("c") ) ;
}

a) abc
b) abc abc abc .....(infinite times)
c) a bc bc bc ....(infinite times)
d) Error


28.    main()
{
int i = 100 ;
printf("%d ", sizeof(i++));
printf("%d ",i) ;
}

Ans.4,100


29.     union tag
{
int a;
char x;
char y;
}name;

int main()
{
name.a=5;
printf("\n x = %d y = %d ",name.x,name.y);   // OUTPUT : 5 5
}



30.    main()
{

#define x 5         //NO ERROR
int b;
b = x;
printf("%d",b);     
}



31.    main()
{
int a; #define y 10     //ERROR
a=y;
printf("%d",a);
}



32.    struct
{
int i;
}node ;


main()
{
printf("%d",node.i);
}

(a). 0
(b). Garbage value
(c). error.
(d). warning


33.     i=5;
i=i++ * i++;
printf("%d",i);

    a)30
b)49
c)25
d)27




34.    i=5;
printf("%d",i++ * i++);

a)30
b)49
c)25
d)37
35.    main()
{
int *p,*q,i;
p=(int *)100;
q=(int *)200;
i=q-p;
printf("%d",i);
}
a)100  b)25   c)0     d)compile error

36.    main()
{
int a=10,b=5;
if(a=a&b)
b=a^b;
printf("a=%d,b=%d",a,b);
}
a)a=0,b=5  
b)a=10 b=5   
37.    int main()
{
            int i=89;
        int *p;     char *t;
        p=&i;
        t=(char *)&i;
    if( *p==*t)
        printf("yes");        //Ans
    else
        printf("no");
}


No comments:

Post a Comment