Total Pageviews

Saturday, 5 May 2012

Pointers


Pointers
Pointer are a fundamental part of C. If you cannot use pointers properly then you have basically lost all the power and flexibility that C allows. The secret to C is in its use of pointers.

C uses pointers a lot. Why?:
  • It is the only way to express some computations.
  • It produces compact and efficient code.
  • It provides a very powerful tool.

C uses pointers explicitly with:
  • Arrays,
  • Structures,
  • Functions.
NOTE: Pointers are perhaps the most difficult part of C to understand. C's implementation is slightly different DIFFERENT from other languages.
 
What is a Pointer?
A pointer is a variable which contains the address in memory of another variable. We can have a pointer to any variable type.

The unary or monadic operator & gives the ``address of a variable''.

The indirection or dereference operator * gives the ``contents of an object pointed to by a pointer''.

To declare a pointer to a variable do:
int *pointer;

NOTE: We must associate a pointer to a particular type: You can't assign the address of a short int to a long int, for instance.


Consider the effect of the following code:

       int x = 1, y = 2;
       int *ip;
       ip = &x;
       y = *ip;
       x = ip;
       *ip = 3;

It is worth considering what is going on at the machine level in memory to fully understand how pointer work. Consider Fig. 9.1. Assume for the sake of this discussion that variable x resides at memory location 100, y at 200 and ip at 1000.

Note A pointer is a variable and thus its values need to be stored somewhere. It is the nature of the pointers value that is new.

Friday, 4 May 2012

Static Variables


Static Variables
A static variable is local to particular function. However, it is only initialised once (on the first call to function).

Also the value of the variable on leaving the function remains intact. On the next call to the function the the static variable has the same value as on leaving.

To define a static variable simply prefix the variable declaration with the static keyword. For example:

  void stat(); /* prototype fn */

               main()
                { int i;

                      for (i=0;i<5;++i)
                             stat();
                }

  stat()
                {    int auto_var = 0;
                     static int static_var = 0;
                    
                     printf( ``auto = %d, static = %d \n'',
                               auto_var, static_var);

                     ++auto_var;
                     ++static_var;
                }

Output is:

              auto_var = 0, static_var = 0
              auto_var = 0, static_var = 1
              auto_var = 0, static_var = 2
              auto_var = 0, static_var = 3
              auto_var = 0, static_var = 4

Clearly the auto_var variable is created each time. The static_var is created once and remembers its value.

Enumerated Types


Enumerated Types
Enumerated types contain a list of constants that can be addressed in integer values.
We can declare types and variables as follows.
enum days {mon, tues, ..., sun} week;
enum days week1, week2;
NOTE: As with arrays first enumerated name has index value 0. So mon has value 0, tues 1, and so on.

week1 and week2 are variables.
We can define other values:

  enum escapes { bell = `\a',       backspace = `\b',  tab = `\t',
               newline = `\n', vtab = `\v',       return = `\r'};

We can also override the 0 start value:

enum months {jan = 1, feb, mar, ......, dec};

Here it is implied that feb =

Unions

Unions
A union is a variable which may hold (at different times) objects of different sizes and types. C uses the union statement to create unions, for example:
                 union number
                             {
                             short shortnumber;
                             long longnumber;
                             double floatnumber;
                             } anumber
defines a union called number and an instance of it called anumber. number is a union tag and acts in the same way as a tag for a structure.

Members can be accessed in the following way:

          printf("%ld\n",anumber.longnumber);

This clearly displays the value of longnumber.

When the C compiler is allocating memory for unions it will always reserve enough room for the largest member (in the above example this is 8 bytes for the double).

In order that the program can keep track of the type of union variable being used at a given time it is common to have a structure (with union embedded in it) and a variable which flags the union type:

An example is:

              typedef struct
                             { int maxpassengers;
                             } jet;

              typedef struct
                             { int liftcapacity;
                             } helicopter;

              typedef struct
                             { int maxpayload;
                             } cargoplane;

               typedef union
                             { jet jetu;
                               helicopter helicopteru;
                               cargoplane cargoplaneu;
                             } aircraft;

              typedef  struct
                             { aircrafttype kind;
                               int speed;
                               aircraft description;
                             } an_aircraft;

This example defines a base union aircraft which may either be jet, helicopter, or cargoplane.

In the an_aircraft structure there is a kind member which indicates which structure is being held at the time. 

Defining New Data Types in C Language


Defining New Data Types
typedef can also be used with structures. The following creates a new type agun which is of type struct gun and can be initialised as usual:

              typedef struct gun
                            {
                            char name[50];
                            int magazinesize;
                            float calibre;
                            } agun;

               agun arnies={"Uzi",30,7};

Here gun still acts as a tag to the struct and is optional. Indeed since we have defined a new data type it is not really of much use, agun is the new data type. arnies is a variable of type agun which is a structure.
C also allows arrays of structures:

              typedef struct gun
                            {
                            char name[50];
                            int magazinesize;
                            float calibre;
                            } agun;

              agun arniesguns[1000];

This gives arniesguns a 1000 guns. This may be used in the following way:

          arniesguns[50].calibre=100;

gives Arnie's gun number 50 a calibre of 100mm, and:

          itscalibre=arniesguns[0].calibre;

assigns the calibre of Arnie's first gun to itscalibre.

Structures


Structures
Structures in C are similar to records in Pascal. For example:

                struct gun
                            {
                            char name[50];
                            int magazinesize;
                            float calibre;
                            };

              struct gun arnies;

defines a new structure gun and makes arnies an instance of it.

NOTE: that gun is a tag for the structure that serves as shorthand for future declarations. We now only need to say struct gun and the body of the structure is implied as we do to make the arnies variable. The tag is optional.

Variables can also be declared between the } and ; of a struct declaration, i.e.:
                struct gun
                            {
                            char name[50];
                            int magazinesize;
                            float calibre;
                            } arnies;

struct's can be pre-initialised at declaration:

struct gun arnies={"Uzi",30,7};

which gives arnie a 7mm. Uzi with 30 rounds of ammunition.
To access a member (or field) of a struct, C provides the . operator. For example, to give arnie more rounds of ammunition:
arnies.magazineSize=100;


  1. What will be printed as the result of the operation below:
    main()
    {
        char *ptr = ” Cisco Systems”;
        *ptr++; printf(“%sn”,ptr);
        ptr++;
        printf(“%sn”,ptr);
    }
    Answer:Cisco Systems
    isco systems
  2. What will be printed as the result of the operation below:
    main()
    {
        char s1[]=“Cisco”;
        char s2[]= “systems”;
        printf(“%s”,s1);
    }
    Answer: Cisco
  3. What will be printed as the result of the operation below:
    main()
    {
        char *p1;
        char *p2;
        p1=(char *)malloc(25);
        p2=(char *)malloc(25);
        strcpy(p1,”Cisco”);
        strcpy(p2,“systems”);
        strcat(p1,p2);
        printf(“%s”,p1);
    }
    Answer: Ciscosystems
  4. The following variable is available in file1.c, who can access it?:
    static int average;
    
    Answer: all the functions in the file1.c can access the variable.
  5. WHat will be the result of the following code?
    #define TRUE 0 // some code
    while(TRUE)
    {
        // some code
    }
    Answer: This will not go into the loop as TRUE is defined as 0.
  6. What will be printed as the result of the operation below:
    int x;
    int modifyvalue()
    {
        return(x+=10);
    }
    int changevalue(int x)
    {
        return(x+=1);
    }
    void main()
    {
        int x=10;
        x++;
        changevalue(x);
        x++;
        modifyvalue();
        printf("First output:%dn",x);
        x++;
        changevalue(x);
        printf("Second output:%dn",x);
        modifyvalue();
        printf("Third output:%dn",x);
    }
    Answer: 12 , 13 , 13