Saturday, August 30, 2008

Static and Dynamic data structures

Hope my simple introduction to data structures was informative to you. Now lets see the two methods by which an data structure can operate

Note: If you need a introduction on data structures please click here

Look, the major function of data structure is to handle data which are.
  1. Store
  2. Manipulate
  3. Retrieve
  4. Delete
Consider the first function , "Storing". (If you don't understand the other functions for the time being, just ignore it. No problems! :))

The data structure as to save the values which we pass into the memory. This is done mainly using assignment operator.

Example 1: int a = 4;

Here a is an integer data type(a data structure) which stores the value 4

Example 2: char str [ 10 ] = "String"

Here str is a character array data type which stores the value "String"
( In c Strings and character array means the same)

Consider this example

Example3: char *c;
c = (char *) malloc ( sizeof ( char ) * 10 ) ;
c = "String" ;


Here again c is of string data type that stores the value "String". but if you closely observe we use a malloc (memory allocation) function to allocate memory to our data structure c.

Note: If you don't understand the workings of malloc don't panic.It just allocates memory to the variable from the memory heap( memory where the variables are stored). Click here to learn more on malloc function

When we manually allocate memory as in example 3, then such a data structure is called a dynamic data structure. but if the memory is allocated automatically (by the runtime environment of the language) as in example 1 and example2 then the data structure is a static data structure.


Which type of data structures I should use???

The type of data structure you need to use depends on your application. If you know the number of data you need to store beforehand you can use static data structures. On the other hand if you know the size of data only at the runtime its better to use dynamic data structures but writing dynamic data structures is more complex than writing simple ones.

No comments: