Friday, August 24, 2012

Mysterious C : part 2

POINTERS

Type Casting of pointers

Yes it is true that in C one type of pointer can be converted into another. There are 2 categories of pointer conversions in C.
(1) those that involve void* pointers and (2) those that don't!

The void* pointer, which is a "generic pointer" is permissible to assign any other type of pointer. And it is also permissible to assign any other pointer type to void* pointer. The void* pointer is used to refer to raw memory(the results of malloc() function) when the semantics of the memory are unknown. No explicit cast is required to convert to or from a void* pointer.

Except for void* all other pointer conversion must be performed with an accompanying explicit type cast. However there are some difficulties.

Example E1
_________________________________________________________________________________
#include<stdio.h>

main()
{
                    double x=101.31754833673,y;
                    int *p;

     /* now we set the integer pointer to point the double x*/

                  p=(int*)&x;
    /*then we try to assign y the value of x via the pointer p*/
    
                  y=*p;
    /*however the above statement doesn't work as expected*/

                 printf("value of y is : %f",y);
}
_________________________________________________________________________________


try this one and see the result.

What really happened was, when we explicitly type casted the double x into integer pointer p, the pointer p points only to 2 bytes of data as it is an integer pointer, so in the background p points only to 2 bytes of data of the 8 byte long x-- which means the remaining 6 bytes of x were chipped off!

Work W1

OK now here is a work for the reader, in our previous example E1 we used a type cast of double value to an integer pointer- try out what happens if the reverse is done, that is try type casting of an integer value to a double value.


Pointers to functions

Dear friend this a confusing yet powerful feature of our C. Every function has a physical location in memory, like we directly assign a variable an address which stores the value we can manipulate. We can use pointers to use functions.Function pointers also allow functions to be passed as arguments to other functions- now wait functions as arguments? that's weird! isn't it?

We can obtain the address of a function directly from its name without any arguments or parentheses. This is similar to getting the address of an array from its name without its size or square brackets.

Example E2

_________________________________________________________________________________ 

#include<stdio.h>
#include<string.h>

void check(char a*,char b*,int(cmp*)(const char*,const char*))
{
                 printf("Testing for equality.\n");
                 if(!(cmp*)(a,b))
                              printf("Equals");
                 else
                               printf("Not equals");
}

main()
{
                 char s1[100],s2[100];
                 int (*p)(const char*,const char*);             /*function pointer*/

                 p=strcmp;                                                /*assign address of function strcmp to p*/
                 printf("enter the strings");
                 gets(s1);
                 gets(s2);

                 check(s1,s2,p);                                       /*pass address of strcmp via p*/
}

_________________________________________________________________________________  

remember to put the parentheses around *p and *cmp, it is necessary inorder for the compiler to interpret their corresponding declarations.

Inside the check(), the expression

                 (*cmp)(a,b);
calls strcmp, which is pointed to by cmp, with a & b as arguments. Another simpler syntax for the above stt is :              

                  cmp(a,b);
but it is wise to use the first one, because the reader can easily understand that cmp is a function pointer $ not a function.

You can also call check() using strcmp directlylike

                 check(s1,s2,strcmp);
which eliminates the nerded for an additional pointer variable.

You may wonder why anyone would use such a style of programming which introduces lots and lots of confusion. However, at times it is advantageous to pass functions as parameter s or to create an array of functions. For example, when an interpreter is written, the parser(the part which processes the expression) often calls various supporting functions, such as those that compute mathematical operations(sine, cosine, tangent, etc), perform I/O, or access system resources. Instead of having a large switch statement with all of these function listed in it, an array of function pointers can be created. Here the proper function is selected by its index

The Restrict Qualifier for Pointers!

The C99 standard has added a new type qualifier that applies only to pointers: restrict. 

A pointer qualified by restrict is initially the only means by which the object it points to is accessed. Access to the object by another pointer can occur only if the second pointer is based on the first. Thus, access to the object is restricted to expressions based on the restrict - qualified pointer. Pointers qualified by restrict are primarily used as function parameters or to point to memory allocated via malloc(). By qualifying a pointer with restrict, the compiler is better able to optimize certain types of routines. For example, if a function specifies two restrict - qualifier pointer parameters, then the compiler can assume that the pointers point to different(that is non-overlapping) object. The restrict qualifier doesn't change the semantics of the program. 


Common Mistakes that we make with pointers.

Pointers are a mixed blessing. They give you tremendous power, but when a pointer is used incorrectly, or contains the wrong value, it can be a very difficult bug to find(such pointers are usually known as wild pointers). 

BELIEVE ME NOTHING WILL GET YOU INTO MORE TROUBLE THAN A WILD POINTER!

The classic example of a pointer error is the uninitialized pointer.

E3 
_________________________________________________________________________________

/*Believe it or not this junk of program is absolutely wrong */

main()
{

          int x,*p;
          x=10;

          *p=x;                             /*ERROR p is not initialized!*/
}
_________________________________________________________________________________

This program assigns the value 10 to some unknown memory location. Here is the reason. Since the pointer p has never been given a value it contains an unknown(garbage) value when the assignment *p=x takes place. This causes the value of x to be written to some unknown memory location. This type of problem often goes unnoticed when the program is small. because the odds are in favor of containing a "safe" address - one that is not in your code, data area, or Operating system. However as your program grows the probability increases of p pointing to something vital. Eventually, your program stops working.

A second common error is caused by a simple misunderstanding of how to use a pointer. Consider the following:
E4
_________________________________________________________________________________

main()
{

           int x,*p;
           x=10;
           p=x;
           printf("%d",*p);

}
_________________________________________________________________________________

Here p=x is wrong. The statement assigns the value 10 to the pointer p. However, p is supposed to contain an address, not a value. To correct the program, write    p=&x.

Making any comparison between pointers that do no point to the same object may yield unexpected results. For example:

E5
_________________________________________________________________________________

main()
{
         char s[100], y[100];
         char *p1,*p2;

         p1=s;
         p2=y;

        if(p1<p2)
        {
                   - - - - -
        }

        ---------
}
_________________________________________________________________________________

The above given program quite an invalid concept, think why ?

A related error results when you assume that two adjacent arrays may be indexed as one by simply incrementing a pointer across the array boundaries. For example:

E6
_________________________________________________________________________________

main()
{
           int first[10],second[10];
           int *p,t;

           p=first;

           for(t=0;t<20;++t)
                     *p++ = t;
}
_________________________________________________________________________________

This is not a good way to initialize the arrays first  and second with the numbers 0 through 19. Even though it may work on some compilers under certain circumstances, it assumes that both arrays will be placed back to back in memory with first first. This may not always be the case.

This is your turn, try to find the bug in this program!

E7
_________________________________________________________________________________

/* this program has a bug*/

#include<stdio.h>
#include<string.h>

main()
{
          char *p1;
          char s[100];

          p1=s;

          do
          {
                       gets(s);

                      /* print the decimal equivalent of each character in s */

                                    while(*p1)
                                                 printf("%d", *p1++);
          }
          while(strcmp(s,"done"));
}
_________________________________________________________________________________

The problem is that p1 is assigned the address of s only once, outside the loop. The first time through the loop, p1 points to the first character in s. However, the second time through, it continues where it left off because it is not reset to the start of s. This next character may be part of the second string, another variable, or a piece of the program! The proper way to write this program is by placing the assignment operation p1=s as the first statement of the do-while loop.

Wednesday, August 8, 2012

Mysterious C- Part:1

Guys, this blog is for those who know the C language of Dennis Ritchie - for all those Software engineers out there who surely learned the basics the C language but not the mysterious parts of it. The C language has several things that we don't even know yet. I think may be the great Dennis Ritchie will be the only one who ever knew it!

Ok i will now stop my chats and start the investigation of the mysteries of C!

oh ! i did forgot to write the caption---- "Most of the things that you don't know about C!"
 C was invented and first implemented by Dennis Ritchie, that part we all know. But he implemented it on a DEC PDP-11 machine that used the UNIX operating system is know to a very few people!

C is not a block structured but structured programming language. Now the question arises what's the difference between structured and block structured? "A block structured language permits procedures or functions to be declared inside other procedures or functions." However, since C does not allow the creation of functions within functions, it cannot formally be called block structured isn't it?

We will discuss about 2 versions of C: the C89 and C99. The standard C89 consists of only 32 keywords, remember guys "our great C has only 32 keywords!" Hey why don't you guys give a shot in recalling those 32 key words! recalling more that 25 is the sign of a very talented programmer- many don't make it not even i couldn't come up with 20 key words even after using C for the past 4 years!
Here they are this time try to remember them it may be useful when you go for an Interview to form a career in IT sector.

auto     break     case     char    const    continue     default     do     double    else     enum     extern     float     for     goto     if     int     long     register     return    short     signed     sizeof     static     struct    switch     typedef     union     unsigned      void     volatile     while

C99 also include the following 5 keywords too:
_Bool     _Complex     _Imaginary     inline    restrict


C's Memory Map

A C program (Compiled) creates and uses 4 logically distinct parts of memory.

First:     The memory that actually holds the programs executable code.

Second:     Memory where the global variables are stored.

Third:     The stack, used for a great many things while your program executes. It holds the return addresses     of function calls, arguments to functions, and local variables.It will also save the current state of the CPU.

Fourth:     The heap, a region of free memory that your program can use via C's dynamic memory allocation functions.


In C89, you must declare all local variables at the start of a block, prior to any "action" statements. However, in C99 you can declare local variables at any point within a block, prior to the first use(just as we do in JAVA).

The Four C Scopes

Standard C defines 4 scopes that determine the visibility of an identifier. They are summarized as:
  1. File Scope: Starts at the beginning of the file and ends with the end of the file. It refers only to those identifiers that are declared outside of all functions. File scope identifiers are visible throughout the entire file. The variable with this kind of scope are known as the "Global Variables".
  2. Block Scope: Begins with the opening { of a block and ends with its associated closing }. However block scope also extends to function parameters in a function definition. Variables with block scope are local to their block.
  3. Function Prototype Scope: Identifiers declared in a function prototype; visible within the prototype.
  4. Function Scope: Begins with the opening { of a function and ends with its closing }. Function scope applies only to labels. A label is used as the target of a 'goto' statement, and that label must be within the same function as the goto.

Hexadecimal and Octal constants

C allows you to specify integer constants in hexadecimal or octal instead of decimal. A hexadecimal constant must consist of a 0x followed by the constant in hexadecimal. An octal constant begins with a 0.
eg :-
                                       int hex = 0x80            /* 128 in decimal*/
                                       int oct = 012              /*10 in decimal*/

The Comma Operator

The comma operator strings together several expressions. The left side of the comma operator is always evaluated as void. This means that the expression on the right side becomes the value of the total comma-separated expression. For example:  
                                                X = (Y=3,Y+1);
first assigns Y the value 3 and then assigns X the value 4. The parentheses are necessary because the comma operator has a lower precedence than the assignment operator. 

The Dot(.) and the Arrow(->) Operators

The dot operator is used when working with a structure or union directly.
eg :-      struct_name.element_of_structure = value;

The arrow operator is used with a pointer to a structure or union, that is, arrow operator is used with a pointer of pointer.
eg :-     int **ptr;
            int *abc;
            struct student.roll_no = 5;

            abc = &student.roll_no;
            ptr -> abc;
now ptr will be containing the address of abc, while abc will be containing the address of student.roll_no.

Variable Length Arrays

In C89 the size of an array is fixed at compile time. However, this is not the case for C99, which adds a powerful new feature to arrays: variable length. In C99 you can declare an array whose dimensions are specified by any valid expression, including those whose value is known only at run-time. Only local arrays (that is those with block scope or prototype scope)can be of variable length.
eg :-
          void newfunction(int x)
          {
                        char str[x];          /* A variable length character array*/
                        /* . . . */
          }

Friends i will be back soon with more mysterious parts of C language soon, until then wait!!!

Monday, August 6, 2012

Introduction to Latex-part:3

For truly impatient ones here's a sample code to try out!

\documentclass{article}
\begin{document}
Hello World!
\end{document}

The code will be explained later.

Spaces

"Whitespace characters, such as blank or tab, are treated uniformly as "space" by Latex. Several consecutive white spaces are treated as one "space". White space at the start of a line is generally ignored and a single line break is treated as "whitespace". An empty line between the two line of text defines the end of the paragraph. And several empty lines are treated as one empty line.

Special Characters

The following symbols are reserved characters that either have a special meaning under Latex or are unavailable in all the fonts. if you enter them directly in your text, they will normally not print, but rather make Latex do things you did not intend.
........................................................................................................................................
|#  $  %  ^  &  _  {  }  ~  \
........................................................................................................................................

The only way for you to insert these characters in your document is to prefix them with a backslash(\).

for eg:- \#  \%  \$ ...

Another funny thing is that you cannot use "\\" to print \ in your document. Because \\ is used for newline in Latex. For you to insert a backslash in your document try:
                              "\backslash"

Latex Environment

Environments in Latex have a role that is quite similar to commands, but they usually have effect on a wider part of the document. Their syntax is:

\begin{environmentname}
text to be influenced
\end{environmentname}

Between the \begin and the \end you can put other commands and nested environments.

Comments

When Latex encounters a % character while processing an input file, it ignores the rest of the current line, the line break and all white space at the beginning of the next line.

Introduction to Latex-part:2

Latex is a macro package based on TeX created by Leslie Lamport. Its purpose is to simplify TeX typesetting, especially for documents containing mathematical formula. Many authors have contributed extensions, called packages or styles, to Latex. some of them are bundled with most TeX/Latex software distributions; more can be found in the Comprehensive TeX Archive Network(CTAN-(http://www.ctan.org)).

Prerequisites

 At a minimum, you'll need a TeX distribution, a good text editor(KILE) and a DVI or PDF viewer

How to install a Latex/TeX editor?

The first thing you will be needing is to look for KILE or TeX maker or any thing you find which is good for you, but remember the coding styles aren't the same for all kinds. You can get a list of few editors for the link (list of editors) . Here i prefer KILE for the work.

Windows 

TeXLive and MikTex have easy installers that take care of setting up environment and downloading packages

 Linux

You can install KILE in your Linux machine using your software center. The installation size is about 9MB.

MacOS 

Download MacTeX.mpkg.zip on the MacTeX page (http://www.tug.org/mactex/ )

Since Latex comprises a group of TeX commands, Latex document processing is essentially programming. You create a TeX file in Latex Markup, The Latex macro reads this to produce the final document.

We will begin with our first program in the next blog!
.

Introduction to Latex-part:1

LET US BEGIN!


Yes guys its Latex (and its pronounced as "LAH-TECH")! This very programming language created by Donal Knuth is used to typeset your documents attractively and consistently.

You may think "why do i need to type so much codes to create a document while i can do it with my user friendly MS-Word or open office Writer? I can simply convert it into PDF by saving it in pdf format in MS, or just by clicking the convert to pdf in open office or better use a doPdf application!"

But dear friend i would say that Latex gives me a care free attitude when i am preparing my document. You see when we use the Word or Writer application, we need to give a greater care for the alignment, paragraph spacing, line spacing, different fonts, page numbers, foot notes, citations, even for inserting pictures. More over the style of document that Latex gives you is like a professional document. If you are in a competitive environment the document prepared using Latex will give you an upper hand over the ordinary documents.

Look more for my blogs to catch up with Latex!