Saturday, February 12, 2011

Array and Pointer in C++:


Array and Pointer in C++:
          Array:
                Array is a data structure that store a number of data items as a single entity (object). The individual data items are called elements and all of them have same data types. Array is used when multiple data items that have common characteristics are required (in such situation use of more variables is not efficient). In array system, an array represents multiple data items but they share same name. The application of array is similar to that in C. The only difference is while initializing character arrays. When initializing a character array in C, the compiler will allow us declare the array size as the exact length of the string constant. For example:
                 char name[5]=”shyam”;
is valid in C and null character \0 is added at the last of array automatically. But in C++, the size should be one larger than the number of characters in the string. i.e.
   char name[6]=”shyam”;

Pointer:
                  A pointer is a variable that stores a memory address of a variable. Pointer can have any name that is legal for other variable and it is declared in the same fashion like other variables but is always preceded by ‘ *’ ( asterisk) operator. Pointers are declared and initialized as in C. The additional feature of C++ is that has concept of constant pointer and pointer to constant. The constant pointer is defined as
Data_type * const ptr_name;
An example:
  void main()
     {    int j=10;
    int *const ptr=&j; //constant pointer
    *ptr=20;//OK
     ptr++;   //Error
             }
Pointer to Constant:
It is defined as
     Data_type const *ptr_name;
An example:
void main()
     {

    int const j=10;
    int const * ptr=&j;// pointer to constant
     *ptr=20;//Error
     ptr++;   //OK
      }

No comments:

Post a Comment