The greatest mistake you can make in life is to be continually fearing you will make one

Tuesday 9 March 2010

C Question of the Day -Array

1.What is the output of the following program?
#include<stdio.h>
main()
{
    char name[]="sun";
    int i;
   for(i=0;name[i];i++)
    {
        printf("%c%c%c%c\n",name[i],*(name+i),*(i+name),i[name]);
    }
    return 0;
}
Solution
ssss
uuuu
nnnn

name[i],*(name+i),*(i+name),i[name] are all different ways of expressing the array element.Here name is the base address.i is the index number


2.What is the output of the following program?
#include<stdio.h>
main()
{
    int num[]={2.3,3.4,4,5.6,7};
    int i,*x=num,*y=num;
   for(i=0;i<5;i++)
    {
        printf("%d",*num);
        ++y;
    }
    for(i=0;i<5;i++)
    {
        printf("%d",*x);
        ++x;
    }
    return 0;
}
Solution
2222223457Initially pointer num is assigned to both x and y.In the first loop the pointer y is incremented and the num value is printed.So the value 2 is printed 5 times. In the 2nd loop the pointer x is incremented and the value in x is printed. so the integer values 23457 will be printed


3.What is the output of the following program?
#include<stdio.h>
main()
{
    char str[]="Welcome";
    display(str);
    return 0;
}
void display(char *str)
{
    printf("Text=%s\n",str);
}
Solution
Compiler Error: Type mismatch in redeclaration of function display
In the main function when the function display is encountered,the compiler doesnt know anything about the function display. It assumes the arguments and return types to be integers(default). But in the actual function display the arguments and the return type contradicts with the assumption. Hence a compile time error occurs.


4.What is the memory allocated by the following definition?
[Assuming size of integer is 4 bytes]
int (*p)[10];
Solution
P is a array of 10 integer pointers. 40 bytes memory is allocated


5.What is the memory allocated by the following definition?
int (*p)(10);
Solution
P is a pointer to a function. size of a pointer is 4 bytes. So 4 bytes memory is allocated.

No comments:

Post a Comment