C Objectives

1) Why does this code: char *p = "hello, world!";
      p[0] = 'H';
       crash?

Explanation:
String constants are in fact constant. The compiler may place them in nonwritable storage, and it is therefore not safe to modify them. When you need writable strings, you must allocate writable memory for them, either by declaring an array, or by calling malloc. Try
char a[] = "hello, world!";


2) Why is this loop always executing once? 
     for(i = start; i < end; i++);
    {
            printf("%d\n", i);
    }

Explanation:
The accidental extra semicolon hiding at the end of the line containing the for constitutes a null statement which is, as far as the compiler is concerned, the loop body. The following brace-enclosed block, which you thought (and the indentation suggests) was a loop body, is actually the next statement, and it is traversed exactly once, regardless of the number of loop iterations.


3) What is the output?
    main()
    {
            static int var = 5;
            printf("%d ",var--);
            if(var)
                        main();
    }
   Answer:
    5 4 3 2 1
   
    Explanation:  
    When static storage class is given, it is initialized once. The change in the value of a static   
    variable is retained even between the function calls. Main is also treated like any other 
    ordinary function, which can be called recursively. 

4) What is the out put?
    main()
   {
            char *p;
            printf("%d %d ",sizeof(*p),sizeof(p));
   }

  Answer:
  1 2

  Explanation:
  The sizeof() operator gives the number of bytes taken by its operand. P is a character pointer, 
  which needs one byte for storing its value (a character). Hence sizeof(*p) gives a value of 1. 
  Since it needs two bytes to store the address of the character pointer sizeof(p) gives 2.

No comments:

Post a Comment