|
C Programming Reference >> C Basic Programming Tutorials >> Arrays And Stringquisite Knowledege 28/05/07 - 4984 Views - Ratings : Arrays in C is a group of same type of variables refrenced under a common name using a index. String in C on other hand is another name for char array terminated with a null character and has some special properties. Both Arrays and C are stored in continous memmory location and can be combined with pointers to improve code efficiency. Also array can single or multidimension widening the field of situation which they can applied to. C Array and C string find wide application in c programming and forms an integral part of c programming which you should master. Contents - 1. Single Dimension Array 2. Two Dimensional Array 3. Multi Dimension Array 4. Passing Array as Parameter 5. Initalizing Array 6. Variable Length Array 7. Strings 8. Pointers With Array 9. Pointers With Strings Also known as 1-D array because of its logical representation of 1 Dimension data. The genral form of declaration of 1-D Array is - type name [size];
Here 'type' is the type of the varibles collected under the common name. 'name' is the common name used to refrence the collected variables. 'size' is the size of the array or the number of variables collected in the array. One important thing is that in this declaration the size should be constant hence making array of this type static with fixed size. This may seem to be a very big restriction on arrays but dynamic variable length arrays can be created in C using dynamic memmory allocation. Also a new feature in C99 lets you create variable length arrays with great ease. Each element in the array is stored in contiguous memmory location. Total size of array is product of size of the each variable and number of each variable. Diagram below shows the logical memmory representation of 1-D Array (A - Array Name , X - Array Starting Memmory Location, V - Size of each element in Bits)..
Elements in array are accessed thorugh an index with valid value 0 to n-1 if n is the size of the array. One other point to be always kept in mind is that the array boundary can be overrunned since C provides no boundary checking and it is a sole responsibility of the programmer. This is a very dangerous situation because your code is modifying memmory outside of what is allocated to it. You may write into some critical data, Operating System Memmory, Stack etc., which may lead to severe program and O.S. crashes. Following C Source Code shows how to use a one dimensional array in C.
Next in complexity to one dimensional array is Two dimensional array, also known as 2-D array. In simplest terms two dimensional array is an array of one dimensional arrays. The genral form of declaration of 2-D Array is - type name [size1] [size2];
Here' size1' is the number of 1-D Arrays and 'size2' is the size of each of that 1-D Array. 2-D arrays can be mentally represented as a matrix with 'size1' number of rows and 'size2' number of columns. This can be shown in the figure below -
Total size of the 2-D array = size1 * size2 * size of each variable. In 2-D array also the index begins with 0 for both parameters. Row value can have possible values 0 to size1 - 1 and columns can have possible values from 0 to size2 - 1. C Source code below shows the declaration and input/output operations on a 2-D array.
C Programming language allows more than 2-D array where most of other languages of its class doesnot showing that C is designed to allow scope fot infinite applications. The general form of declaration of Multidimension array are - type name [size1] [size2] .... [sizeX]; The array of type above is called X-D array. Size of this X-D array = size1 * size2 * size3 * ... * sizeX * size of each variable. Though allowed array of greater dimension than 3-D is not used because size of the array increases exponentially as dimension increases. Also time to access array indexes increases decreasing the programs efficiency. Following diagram shows logical memmory representation of a 3-D array as array of 2-D arrays -
C Source Code below shows the declaration and input/output operations on a 3-D array.
In C entire array cannot be passed as parameter to function entirely. Instead only the base address of the pointer is passed as an argument. This leads to restriction that arrays can be passed only by call by refrence method unlike any other variables which can be passed both by call by refrence and call by value. This restriction can be easily overcomed by declaring passed argument as constant pointer making the function unable to modify the parameter passed simulating call by value to certain extent. General form passing array as parameter is - return_type function_name (name [size1] [size2] .... [sizeX]); Also the left most size (size1) is optional because compiler can calculate its value from the size of array but rest of the sizes are neccesary so another genral form is - return_type function_name (name [ ] [size2] .... [sizeX]); C source code below shows the passing of a 1-D, 2-D and 3-D array as parameter to functions.
Values in array can be initialize at the time of thier declaration. This is important because they may contain garbage value if not initalized properly and thier usage may be dangerous. Some compilers make sure that unintialized values be 0 or NULL. The general form of array initalization is - type name [size1] [size2] .... [sizeX] = { values}; values is a comma seprated list of constants or variables (allowed only in C99), which in case of multi dimensional array is in subaggregated form. If array is half or partially intialized the rest of the values are automatically changed to zero or NULL. C Source code below shows the intialization of an 1-D and 2-D array.
One thing that can be noted is that during intialisation that left most index is optional ( that means all index in 1-D Array). This is because the compiler automatically set its value to the minmum value of the size required to store all the initialization safely. This feature provides a innate advantage of overcoming the human error of wrong index value calculation. Now we re-write the C Source Code above to show the C feature of unsized array intialization. The general form of unsized array initalization is - type name (name [] [size2] .... [sizeX]) = { values};
As discussed above the size of the array has to be constant otherwise program wont compile. This imposes a severe instruction on the array because its size is limited at compile time. As a result the array formed is static who's size cannot be niether decreased nor increased, this is often against what is required because in many programs size of the array required is known only at run time. For overcoming this restriction we use variable length array whose length can be varied at run time. There are two methods for this and latter one is applicable only in C99. In first method we use dynamic memmory allocation which will be discussed latter in detail. We take a quick look here how it can solve the problem. We will use malloc function to gets us memory for the array dynamically and the amount of memory fetched is also calculated at run time based on parameter passed to the function. We also use a little use of pointers which is dicussed in details in next tutorial. C Source Code below shows the potential use of dynamic memory allocation to create variable length array.
What is achieved above can also be done in a simpler way using a new innovative widely applicable programming construct introduced in C99. This construct is itself called variable length array and is used to create variable length arrays. One important restriction is that they can create only local dynamic array ie. global scope dynamic array is not allowed. They work because they allow a variable to be used as declaring array size whos value is evaluated at runtime. C Source Code below shows the correct use of C99's variable length array construct to create dynamic arrays.
Now being well equiped with knowledge about arrays, strings should be a piece of cake for you. String in simplest term is a one dimensional array of characters terminated by a null character ( '\n' ). For safe use size of this string should be one greater than the maximum size string going to be stored in this character array. String in C is equvialent to a real world sentence made by combination of various characters including spaces. The genral form of declaration of String variable is - char name [size];
Strings like other arrays can be initialised in both normal and unsized way. The general form of string initalization is - char name [size] = "value"; The general form of unsized string initalization is - char name [] = "value"; Also a string variable though can be accesed (Input/Output) character by character using a loop but generally they are not. The reason being that both printf and scanf provides a simple way of string input/ouput using a %s specifier. You dont have to worry about NULL character because the compiler would automatically place it on the desired position. Also string manipulation can be done very easily using some predefined functions available in header <string.h>. C Source code belows shows the general use of Strings.
Also a 2-D String Variable can be created which can be logically percieved as Array of strings. General form of declaration of Array of string is - char name [SIZE1] [SIZE2]; Here SIZE1 indicates the number of strings each having a maximum length of SIZE2. Basic functionality of Arrays of String can be seen in C Source Code Below.
Arrays and pointers are very intimately connected. Most important point to remeber is that array name without the brackets is the base address of that array or adress of its first (0th) element. This address can be stored in the pointer. More fading this subtle diffrence is that pointer can also be used with brackets to index array as if it was an array name. In general access provided by the pointer is faster if pointer arithemtic(which by the way is almost completely diffrent from normal arithemetic)is used for acess. Formula for accesing I th element in a 1-D array is - *(pointer_name + I) Formula for accesing I th row, Jth Column element in a 2-D array is - *(pointer_name + I * Number_Of_Elements_Per_Row + J) And so on , formulae becomes more complicated with increase in dimension of the array. Code below shows how to access a 1-D array using pointers.
Code below shows how to access a 2-D array using pointers.
As mention above the strings which are innately character array also posses a close relationship with the pointers. It goes one more step ahead than arrays because, the c allow you to assign any arbitary length string constant to char pointer. Memmory allocated in this way is dynamic and compiler uses a table calles string table to store them. Memmory provided to this string table is via heap. Code belows show the relations between strings and pointer.
Reader Comments -
|
|||||||||||||||||||||||||||||||||||||