Thursday, May 12, 2016

Basic puzzle questions in C :: MUST KNOWN concepts to every programmers

Basic puzzle questions in C :: MUST KNOWN concepts to every programmers
Please try the below puzzles, which are very basic and also very useful in clearing the concept. Find the answer of all the puzzles in last page.

What will be the output of C puzzles below :-
Q 1>
#include<stdio.h>
int main()
{
  char *p=(char *)malloc(sizeof(char)*4); p="abc";
   char q[]="abc123";
     if(p[0]=q[0])
   {
       printf("%c, %c\n",*p,*q);
   }
}

Q 2>
#include<stdio.h>
int main()
{
  char *p=(char *)malloc(sizeof(char)*4); p="abc";
   char q[]="abc123";
     if(q[0]=p[0])
   {
       printf("%c, %c\n",*p,*q);
   }
}


Q 3>
main(){
    int num[] = {1,4,8,12,16};
    int *p,*q;
    int i;
    p =  num;
    q = num+2;
    i = *p++;
    printf("%d, %d, %d\n",i, *p, *q);
}

Q 4>
main(){
char *a[4]={"jaya","mahesh","chandra","swapant"};
int i = sizeof(a)/sizeof(char *);
printf("i = %d\n", i);
}

Q 5>
void fun(int *a, int *b)
{
 int *t;
 t=a;
 a=b;
 b=t;
printf(%d, %d\n",*a, *b);
}
main()
{
     int a=2;
     int b=3;
     fun(&a,&b);
     printf(%d, %d\n",a, b);
}

Q 6>
main(){
    int i =0;
    i = 2+3, 4>3, 3;
    printf("%d", i);
}

Q 7>
main(){
    printf("%u", -1);
}

Q 8>
struct ABC{
    float a:10;
    int b:6;
    char c;
} structure;
int main(){
    int i = sizeof(struct ABC);
    printf("%d", i);
}

Q 9>
#include<stdio.h>
int main() {
    char x[] = "abc";
    char *y = x;
    *y ='1';
    printf("%s",y);
}

Q 10>
main(){
    int i =0;
    i = 4>3, 2+3, 3;
    printf("%d", i);
}

Q 11>
#include<stdio.h>
void fun(int str,...);
int main()
{
    fun(6,"Hello","World","5","6","7","8");
    return 0;
}
void fun(int str,...)
{
    int i;
    int *n=&str;
    for(i=1;i<=str;i++)
    printf("%s ",*(n+i));
    return 0;

}

ANSWERS::
1> Segmentation Fault
   Reason-> We can't assign value to pointer valriable like this.
Different ways to assign value to pointer valriable. 
char *p="Hello World";
char *p=new char[11];  p="Hello World";
Wrong ways which lead to segmentation fault::
p[0]='a'; if(p[0]=='a'){};  *p='a'; if(*p=='a'){};
2> a, a

3> 1, 4, 8

4> 4

5> 3, 2
   2, 3
6> 5
   Explanation:: It stores only the first value.

7> 4294967295   :: As the size of unsigned int is from 0 to 4,294,967,295. -1 will print the back side of zero i.e. 4294967295.

8> Compilation Error:: We cannot use but filed for Float.

9> 1bc

10> 1  ::4>3 return 1 as it is true.

11> Hello World 5 6 7 8


Please comment if you find any thing wrong also please post the questions which you feel need to be shared.

No comments:

Post a Comment