Sunday, October 31, 2010

Data Structures Part 1

What is the difference between char *a and char a[]? 

         
There is a lot of difference!

char a[] = "string";
char *a = "string";


The declaration char a[] asks for space for 7 characters and see that its
known by the name "a". In contrast, the declaration char *a, asks for a 
place that holds a pointer, to be known by the name "a". This pointer
"a" can point anywhere. In this case its pointing to an anonymous 
array of 7 characters, which does have any name in particular. 
Its just present in memory with a pointer keeping track of its location.




char a[] = "string";

   +----+----+----+----+----+----+------+
a: | s  |  t |  r |  i |  n |  g | '\0' |
   +----+----+----+----+----+----+------+
   a[0] a[1] a[2] a[3] a[4] a[5] a[6]


char *a = "string";

+-----+          +---+---+---+---+---+---+------+
|  a: | *======> | s | t | r | i | n | g | '\0' |
+-----+          +---+---+---+---+---+---+------+
Pointer          Anonymous array



It is curcial to know that a[3] generates different code depending 
on whether a is an array or a pointer. When the compiler sees the 
expression a[3] and if a is an array, it starts at the location "a", 
goes three elements past it, and returns the character there. When
it sees the expression a[3] and if a is a pointer, it starts at the
location "a", gets the pointer value there, adds 3 to the pointer value, 
and gets the character pointed to by that value. 

If a is an array, a[3] is three places past a. If a is a pointer, 
then a[3] is three places past the memory location pointed to by a.
In the example above, both a[3] and a[3] return the same character, 
but the way they do it is different! 

Doing something like this would be illegal.


char *p = "hello, world!";
p[0] = 'H';

Thursday, October 28, 2010

C Puzzles Part 4

Here is the next set of C Riddles.  It contains questions like Find The OutputSingle Word Answer, and some Write A Program type.  I have not include the answer or the solutions for any of the questions as it does not make any sense.   If you could not arive at the  Solution, then you can mail me the question.   Also, your contributions to build this site with more Riddles will be awaited.   Happy Riddling!!!!


1. What Would be the output of the following program?


void main()
{
    const int x=get();
    printf("%d",x);
}
get(){ return(20);}
A. 20 B. Garbage Value
C. Error D. 0
2. Is the following program valid in C?


void main()
{
    printf("%d",main);
}
A. Yes B. No
3. If i and k are two integer variables with i initialized to 2,
        what will be the value of k and i after the assignment statement


k = ++i + i++ * ++i
A. k=13, i=5 B. k=20, i=5
C. k=16, i=5 D. None of the above
4. What would be the pointer expression for referring the same statement as
        a[i][j][k][l]


A. ****( a+i + j + k + l )
B. *( *( *( (*a+i) + j ) + k ) + l )
C. *( *( *( *(a+i) + j ) + k ) + l )
D. None of the above
5. What is the value returned by sizeof(a) if a is defined as
        int a[' ']


A. 32 B. 0
C. 64 D. Garbage value
6. What would be the output of the following program?


void main()
{
    float a=0.7;
    if( a < 0.7f )
        printf("This is From C");
    else
        printf("This is From C++");
}
A. This is From C B. This is From C++
C. Error D. None of the above
7. What is the output of the following program?


void main()
{
    printf("%f",sqrt(36.0));
}
A. 6.0 B. 6
C. 6.000000 D. Garbage value
Answer the following Questions ( Quest #8 to Quest #12 ):
8. Which is the only keyword in C which is also an Operator?
9. Write the smallest possible recursive program in C.
10. In which Header file is the NULL MACRO defined?
11. What does the following declaration signify?


void ( *f ) ( int, void ( * )() );
12. What is the difference between the declarations


char *const ptr
and char const *ptr
Find the Output in the following programs ( Quest #13 to Quest #25 ). If any of the following programs does not get compiled or generate error, just point out the errors.
13. #define CONDITION if ( c == 8 ) printf(" C IS EQUAL TO 8")


void main()
{
     int a=2, b=3, c=4;
     if ( a > b )
         CONDITION;
     else
         printf("A IS NOT EQUAL TO B");
}
14.        void main()


{
    int x=1, y=2;
    switch ( x++, --y, x+=y, y+=x )
    {
    case 2:
        printf("This is Case #2");
        break;
    case 3:
        printf("This is Case #3");
        break;
    case 4:
        printf("This is Case #4");
        break;
    default:
        printf("This is Default Case");
  }
}
15.  void main()
          {
              printf("\n %c", "ABCDEFGH"[4]);
              printf("\n %d", printf(5+"SIR MVIT")+10);
              printf("\n %d", printf("\n\n\n%s","Test"));
          }
16.       void main()
          {
              int a, b = 5;
              a=b+NULL;
              printf("%d",a);
              printf("\n%d %d",sizeof(NULL),sizeof(""));
          }
17.       #define CUBE(X) (X * X * X)
          void main()
          {
              int i=2,j;
              j= CUBE( CUBE( i++ ) );
              printf(" i= %d j= %d ",i,j);
          }
18.  void test();
          #pragma exit test 100
          void main()
          {
              int i=10;
              i= ++i;
              printf("i = %d",i++);
          }
          void test()
          {    
              clrscr();
              printf("Kalanjali - 99");
          }
19.  void main()
          {
              int i=20;
              printf("i = %d",i++);
          }
          auto int i=10;
20.       void main()
          {
              int i=10, j=20;
              float x=10, y=20;
              printf("\nSize of ( i + j ) = %d", sizeof(i+j));
              printf("\nSize Of ( i + x ) = %d", sizeof(i+x));
              printf("\nSize Of ( i + y ) = %d", sizeof(x=i+y));
          }
21.  void main()
          {
              char far *near *ptr1;
              char near *far *huge *ptr2;
              char far *huge *near *ptr3;
              printf(" %d %d %d ",sizeof(ptr1),sizeof(*ptr2),sizeof(**ptr3));
          }
22.       void main()
          {
              joke(1,2,3,4);
          }
          joke(int n,...)
          {
              va_list ptr;
              int num;
              num=va_arg(ptr,int);
              printf("%d",num);
          }
23.  #define MAX 100
          void main()
          {
              const int max = 200;
              char string[MAX];
              char array[max];
              array[0] = string[0] = 'A';
              printf("%s %c",string,array[0]);
          }
24.  #define Print(int) printf(" int = %d ", int)
          void main()
          {
              int x=1, y=1, z=1;
              x+=y+=z;
              ++z || ++y && ++z;
              Print(x
              printf(" X= %d Y= %d Z= %d ",x,y,z);
          }
25.       void main()
          {
              int a = 10;
              printf(" Stranger Ahead... \n");
              switch(a){};
              printf("Infinite Loop..?!!");
          }
  
26.    If the following program(test) is run from the command line as
       test one two three what would be the output?
       void main(int argc, char *argv[])
       {
          clrscr();
          printf("\n%s", *++argv);
          printf("\n%s",++*++argv);
          printf("\n%c",**++argv);
       }
27.    If the following program
       void main()
       {
           int x=4;
           float a=3.14;
           char c='A';
           TEST(x,%d);
           TEST(a,%f);
           TEST(c,%c);
       }
       generates the output
       TEST : x = 4
       TEST : a = 3.140000
       TEST : c = A
       then define the MACRO TEST.
28.   Modify the statement
       ( a > b ) ? b= 3 : c= 3;
       and generate the same effect by using the digit 3 only once.
29.   Write a statement using scanf() to accept a string including Blank Spaces.
30.   Write a function int Sum ( int count, int num,... ) which can take any number of integers as arguements and return the sum of them.
31.     Write a program to simulate the Printf function.

Break Ur Mind with C

Friends , Its a place for Ur Mind to play with C.
Come On download each Volume of C problems and get ready to break Ur brain with Us...

Its a best way to make U strong in C Programming...

All The Best.




1    All problems in HTML(456k )orPostScript(1.4M )orPDF(4.0k )
2    All problems in HTML(588k )orPostScript(1.5M )orPDF(120k )
3    All problems in HTML(344k )orPostScript(1.3M )orPDF(4.0k )
4    All problems in HTML(316k )orPostScript(1.3M )orPDF(4.0k )
5    All problems in HTML(384k )orPostScript(2.0M )orPDF(4.0k )
6    All problems in HTML(488k )orPostScript(2.2M )orPDF(4.0k )
7    All problems in HTML(704k )orPostScript(2.9M )orPDF(4.0k )
8    All problems in HTML(676k )orPostScript(600k )orPDF(340k )
9    All problems in HTML(1.8M )orPostScript(4.0k )orPDF(4.0k )
10  All problems in HTML(560k )orPostScript(284k )orPDF(372k )
11  All problems in HTML(476k )orPostScript(4.0k )orPDF(380k )
12  All problems in HTML(1.5M )orPostScript(4.0k )orPDF(2.0M )
13  All problems in HTML(1.2M )orPostScript(4.0k )orPDF(1.4M )
14  All problems in HTML(1.4M )orPostScript(4.0k )orPDF(1.7M )
15  All problems in HTML(1.2M )orPostScript(4.0k )orPDF(1.4M )
16  All problems in HTML(1.2M )orPostScript(652k )orPDF(3.1M )
17  All problems in HTML(1.7M )orPostScript(1.2M )orPDF(2.6M )
18  All problems in HTML(828k )orPostScript(4.0k )orPDF(1.1M )
19  All problems in HTML(1.6M )orPostScript(4.0k )orPDF(1.2M )
20  All problems in HTML(840k )orPostScript(4.0k )orPDF(1.8M )
21  All problems in HTML(2.2M )orPostScript(4.0k )orPDF(372k )

2+3 and 5 are not equal In C

2+3 and 5 are not equal In C

what is the output of the program?


Example Program:

#define Square( X )  ( X * X )

void main( )
    {
        int value1,value2;
        value1 = Square( 2+ 3 );
        value2 = Square( 5 );

        if ( value1 == value2 )
            printf("Equal");
        else
            printf("Not Equal');
    }


Output:
    Not Equal.



Description:

The Macro replaces the code when there is necessity of the code.From the above program, we can able to understand the usage of Macro.

The value of value1 = 11.
The value of value2 = 25.
How ?
When the code Square(X) (X*X) replaces,we get,

Iteration 1:
value1= (2+3*2+3)
Therefore,value1=11.
Iteration 2:
value2= 5 * 5
Therefore,value2= 25.


Conclusion:

So, we come to a conclusion that 2+3 and 5 is not equal always.
And hence,the Macro should be used in appropriate situations,otherwise Macro will give wrong result.



C Puzzles Part 3

Questions 

L2.Q1 : Write the output of this program 

main(){
        int *a, *s, i;
        s = a = (int *) malloc( 4 * sizeof(int));
        for (i=0; i<4; i++) *(a+i) = i * 10;
        printf("%d\n", *s++);
        printf("%d\n", (*s)++);
        printf("%d\n", *s);
        printf("%d\n", *++s);
        printf("%d\n", ++*s);
}

L2.Q2 : Checkout this program result 

void fn(int);
static int  val = 5


main(){
        while (val --) fn(val);
        printf("%d\n", val);
}
void fn(int val){
        static int val = 0;
        for (; val < 5; val ++) printf("%d\n", val);


}L2.Q3 : Can you predict the output of this program ? 
main()
{
        typedef union {
           int     a;
           char    b[10];
           float   c;
        Union
        Union   x, y = { 100 };
        x.a = 50;s
trcpy (x.b, "hello");
        x.c = 21.50;
        printf ("Union 2 : %d %s %f\n", x.a, x.b, x.c);
        printf ("Union Y : %d %s %f\n", y.a, y.b, y.c);
}

L2.Q4 : Print the output of the program 

main()
{
        struct Data {
              int     a;
              int     b;
        } y[4] = { 1, 10, 3, 30, 2, 20, 4, 40};
        struct Data *x = y;
        int i;
        for(i=0; i<4; i++) {
               x->a = x->b, ++x++->b;  
               printf("%d %d\t", y[i].a, y[i].b); 
        }
}

L2.Q5 : Write the output of this program 
main()
{        typedef struct {
               int     a;
               int     b;
               int     c;
               char    ch;
               int     d;
        }xyz;
        typedef union {
               xyz X;
               char y[100];
        }abc;
        printf("sizeof xyz = %d sizeof abc = %d\n",sizeof(xyz), sizeof(abc));

}

L2.Q6 : Find out the error in this code 
#define Error(str)  

printf("Error : %s\n", str); exit(1); 
main()
{        int fd;
        char str[20] = "Hello! Test me";
        if ((fd = open("xx", O_CREAT | O_RDWR)) < 0) 
               Error("open failed");
        if (write(fd, str, strlen(str)) < 0)
               Error("Write failed");
        if (read(fd, str, strlen(str)) < 0)
               Error("read failed");
        printf("File read : %s\n", str);
        close(fd);
}

L2.Q7 : What will be the output of this program ? 
main()
{       int     *a, i;
        a = (int *) malloc(10*sizeof(int));
        for (i=0; i<10; i++) 
               *(a + i) = i * i;
        for (i=0; i<10; i++) 
               printf("%d\t", *a++);
        free(a);
}
L2.Q8 : 
Write a program to calculate  number of 1's (bit) in a given
integer  number  i.e)  Number of 1's in the given  integer's
equivalent binary representation.

Answers 

L2.A1 
The output will be : 0 10 11 20 21
*s++    =>  *(s++)
*++s    =>  *(++s)
++*s    =>  ++(*s)

L2.A2 
Some compiler (ansi) may give warning message, but it will 
compile withouterrors.
The output will be : 0 1 2 3 4 and -1

L2.A3 

This is the  problem  about  Unions.  Unions are  similar to
structures  but it  differs  in  some  ways.  Unions  can be
assigned  only  with one  field at any time.  In this  case,
unions x and y can be  assigned  with any of the one field a
or b or c at one time.  During  initialisation  of unions it
takes  the value  (whatever  assigned  ) only for the  first
field.  So, The statement y = {100}  intialises  the union y
with field a = 100.
In this  example,  all fields of union x are  assigned  with
some  values.  But at any time only one of the  union  field
can  be  assigned.  So,  for  the  union  x the  field  c is
assigned as 21.50.
Thus, The output will be 
        Union 2 : 22 22 21.50
        Union Y : 100 22 22
        ( 22 refers unpredictable results ) 

L2.A4 

The pointer x points to the same location where y is stored.
So, The changes in y reflects in x.
The output will be :

        10 11    30 31    20 21    40 41

L2.A5 

The  output  of  this  program  is  purely  depends  on  the
processor  architecuture.  If the sizeof  integer is 4 bytes
and the size of character is 1 byte (In some computers), the
output will be
        sizeof xyz = 20        sizeof abc = 100

The output can be generalized to some extent as follows,
        sizeof xyz = 4 * sizeof(int) + 1 * sizeof(char) + 
                                           padding bytes
        sizeof abc = 100 * sizeof(char) + padding bytes
To keep the  structures/unions  byte  aligned,  some padding
bytes are added in between  the  sturcture  fields.  In this
example 3 bytes are  padded  between  ' char ch' and 'int d'
fields.  The unused bytes are called  holes.  To  understand
more about  padding bytes (holes) try varing the field types
of the structures and see the output.
 
L2.A6 

Just  try to  execute  this  file as such.  You can find out
that it will exit immediately.  Do you know why?
With  this  hint, we can trace  out the  error. If you look
into the macro  'Error', you can easily  identify that there
are two separete statements without brases '{ ..}'.  That is
the  problem.  So, it exits  after the calling  open().  The
macro should be put inside the brases like this.

#define Error(str)     { printf("Error : %s\n", str); exit(1); }

L2.A7 

This program will fault (Memory  fault/segmentation  fault).
Can you predict Why?
Remove  the  statment  'free(a);'  from  the  program,  then
execute  the  program.  It will run.  It gives  the  results
correctly.

What causes 'free(a)' to generate fault?
Just trace the address  location  of pointer  variable  'a'.
The variable 'a' is incremented  inside the 'for loop'.  Out
side the 'for loop' the  variable  'a' will point to 'null'.
When the  free()  call is made, it will  free the data  area
from the  base_address  (which is passed as the  argument of
the  free  call)  upto  the  length  of the  data  allocated
previously.  In this case,  free()  tries to free the length
of 10 *sizeof(int)  from the base pointer location passed as
the argument to the free call, which is 'null' in this case.
Thus, it generates memory fault.

L2.A8 

main(argc, argv)
int argc;
char *argv[];
{
        int count = 0, i;
        int v = atoi(argv[1]);
        for(i=0; i<8*sizeof(int); i++) 
                       if(v &(1<< } count); v, %d='%d\n",' in 1?s of printf(?No count++;>