Add to Technorati Favorites
Google

Arrays

In today's post, we will see composite data types i.e. built out of built-in primitive data types. One such data type, we have already seen and that was 'Class'. Other composite data types include array, structures, unions, enums, and data types defined using typedef. Let us see each one of them in detail.

Array is a data structure that:
  • stores homogeneous data (i.e. of same data type)
  • in contiguous memory locations
  • each array element can be referred to using a numeric index
Syntax of array declaration:
  • If you know how many elements will be there in array then use following declaration
data-type array_name[size_of_array];

e.g. int marks[3], double height[4], char name[50]; //char array represents string

  • If size of array is not unknown at compile time and will be known at runtime then you have to allocate memory from heap at run-time using following syntax:
data_type *array_name = new data_type[size_of_array];
e.g. int *iarr = new int[3];


Initializing an array (other than char type)
  • At declaration time:
int marks[3]={12,9,4};
  • Otherwise,
marks[0] = 12;
marks[1] = 9;
marks[2] = 4;

Note that first element is referred by index 0. So, if there are 'n' elements in an array then last element of array will be referred by 'n-1' index.

  • For character arrays representing string, last element is '\0'. So, if I want to store my name "Feroz" then I have to declare a char array of size 6 (5 for F,e,r,o,z and last for '\0').
Initialising a char array:
char array can be initialized in any of the following ways:
  • char name[]="Feroz";
  • char name[6]="Feroz";
  • char name[6]={'F','e','r','o','z','\0'};
  • char name[6];
name[0]='F';
name[1]='e';
name[2]='r';
name[3]='o';
name[4]='z';
name[5]='\0';

  • Or, you have to use string functions like
strcpy(name,"Feroz");

There are many more str functions that we will see in later posts.

For strings, C++ provides a more convenient way that is string class. This also we will cover in later posts.

More on Arrays:
  • Arrays can be passed as function arguments and can be returned from a function. But, what is a function? Again wait for later posts.
  • Arrays can be used to implement more complex data structures like stacks, and queues.

  • We can also have array of structures, array of pointers, and multi-dimensional arrays. For example, to represent a mathematical matrix, we require a 2 dimensional array declared as follows:
int matrix[3][4]; // a matrix with 3 rows and 4 columns
matrix[0][0] = 1; //initializing element present in first column and first row.

  • Also, array name is the address of the first element of an array. That means,

array_name is same as &array_name[0].

You will understand this better when we will touch upon the concepts of pointers.

We will discuss other composite types like structures, unions, etc. in subsequent posts.

Till then, keep practising what ever you have learned.

No comments: