C Mistakes – 1D array
Array is one of the important concept in c programming, while learning or practicing 1D Array most of the beginners unknowingly follow incorrect or invalid syntax of array. This tutorial will list out 1D Array : Mistakes in C Programming
C Programming 1D Array : Mistakes
Mistake 1 : Constant Expression Require
#include<stdio.h> void main() { int i=10; int a[i]; }
Consider the above example of 1D Array,
- We are going to declare an array whose size is equal to the value of variable.
- If we changed the value of variable then array size is going to change.
- According to array concept, we are allocating memory for array at compile time so if the size of array is going to vary then how it is possible to allocate memory to an array.
i is initialized to 10 and using a[i] does not mean a[10] because ‘i’ is Integer Variable whose value can be changed inside program.
Value of Const Variable Cannot be changed
we know that value of Const Variable cannot be changed once initialized so we can write above example as as below -
#include<stdio.h> void main() { const int i=10; int a[i]; }
or
int a[10];
Recommanded Article : Compile Time Initializing an Array
Mistake 2 : Empty Valued 1D Array
#include<stdio.h> void main() { int arr[]; }
Consider the above example, we can see the empty pair of square brackets means we haven’t specified size of an 1D Array. In the example array ‘arr’ is undefined or empty.
Size of 1D Array should be Specified as a Constant Value.
Instead of it Write it as -
#include<stdio.h> void main() { int a[] = {1,1}; }
above syntax will take default array size equal to 2. [Refer Article : Section B]
#include<stdio.h> void main() { int a[] = {}; // This also Cause an Error }
Mistake 3 : 1D Array with no Bound Checking
#include<stdio.h> void main() { int a[5]; printf("%d",a[7]); }
- Here Array size specified is 5.
- So we have Access to Following Array Elements - a[0],a[1],a[2],a[3] and a[4]
- But accessing a[5] causes Garbage Value to be used because C Does not performs Array Bound Check.
If the maximum size of array is “MAX” then we can access following elements of an array -
Elements accessible for Array Size "MAX" = arr[0] = . = . = . = arr[MAX-1]
Mistake 4 .Case Sensitive
#include<stdio.h> void main() { int a[5]; printf("%d",A[2]); }
Array Variable is Case Sensitive so A[2] does not print anything it Displays Error Message : “Undefined Symbol A“
C Programming 1D Array Tips
Tip 1 : Use #define to Specify Array Size
#include<stdio.h> #define MAX 5 void main() { int a[MAX]; printf("%d",a[2]); }
- As MAX is replaced by 5 for every Occurrence , So In due Course of time if you want to increase or decrease Size of array then change should be made in
#define MAX 10
Tip 2 : a[i] and i[a] are Same
Visit this article which will explain how to access array randomly using a[i] and i[a].
C Contiguous Memory
What is Contiguous Memory ?
- When Big Block of memory is reserved or allocated then that memory block is called as Contiguous Memory Block.
- Alternate meaning of Contiguous Memory is continuous memory.
- Suppose inside memory we have reserved 1000-1200 memory addresses for special purposes then we can say that these 200 blocks are going to reserve contiguous memory.
Contiguous Memory Allocation
- Two registers are used while implementing the contiguous memory scheme. These registers are base register and limit register.
- When OS is executing a process inside the main memory then content of each register are as -
Register | Content of register |
---|---|
Base register | Starting address of the memory location where process execution is happening |
Limit register | Total amount of memory in bytes consumed by process |
Here diagram 1 represents the contiguous allocation of memory and diagram 2 represents non-contiguous allocation of memory
- When process try to refer a part of the memory then it will firstly refer the base address from base register and then it will refer relative address of memory location with respect to base address
How to allocate contiguous memory ?
- Using static array declaration.
- Using alloc() / malloc() function to allocate big chunk of memory dynamically.
This article could be more useful for understanding the memory management concept in operating system.
C Array Applications
In the previous tutorials we have learnt more about array and type of arrays. In this example we will be learning different array applications in c programming.
C Programming Array Application :
Array is used for different verities of applications. Array is used to store the data or values of same data type. Below are the some of the applications of array -
A. Stores Elements of Same Data Type
Array is used to store the number of elements belonging to same data type.
int arr[30];
Above array is used to store the integer numbers in an array.
arr[0] = 10; arr[1] = 20; arr[2] = 30; arr[3] = 40; arr[4] = 50;
Similarly if we declare the character array then it can hold only character. So in short character array can store character variables while floating array stores only floating numbers.
B. Array Used for Maintaining multiple variable names using single name
Suppose we need to store 5 roll numbers of students then without declaration of array we need to declare following -
int roll1,roll2,roll3,roll4,roll5;
- Now in order to get roll number of first student we need to access roll1.
- Guess if we need to store roll numbers of 100 students then what will be the procedure.
- Maintaining all the variables and remembering all these things is very difficult.
Consider the Array :
int roll[5];
So we are using array which can store multiple values and we have to remember just single variable name.
C. Array Can be Used for Sorting Elements
We can store elements to be sorted in an array and then by using different sorting technique we can sort the elements.
Different Sorting Techniques are :
- Bubble Sort
- Insertion Sort
- Selection Sort
- Bucket Sort
D. Array Can Perform Matrix Operation
Matrix operations can be performed using the array.We can use 2-D array to store the matrix.
[box]Matrix can be multi-dimensional[/box]
E. Array Can be Used in CPU Scheduling
CPU Scheduling is generally managed by Queue. Queue can be managed and implemented using the array. Array may be allocated dynamically i.e at run time. [Animation will Explain more about Round Robin Scheduling Algorithm | Video Animation]
F. Array Can be Used in Recursive Function
When the function calls another function or the same function again then the current values are stores onto the stack and those values will be retrieve when control comes back. This is similar operation like stack.
C Array name is base address
This tutorial is just to show how array name holds a base address of an array.
Array name is base address
Consider the below example of an array in c programming -
#include<stdio.h> void main() { char s[]="cat"; int i; for(i=0;s[i];i++) printf("\n%c %c %c %c",s[i],*(s+i),*(i+s),i[s]); }
Answer -
c c c c a a a a t t t t
Explanation :
- Array name is the base address of the array, here ‘s’ holds the base address of an array.
- ‘i’ is the index number/displacement from the base address.
- Array arr[i] can be Represented as -
arr[i] = *(array name + displacement) = *(arr + i) = Value at (Array name + Displacement) = Value at (Base Address + Displacement)
similarly we can conclude that -
s[i] = *(s + i) i[s] = *(i + s)
Consider the above example with practical example, Suppose we have an array having starting address 1000 -
Now in this case array ‘s’ represents an array of character so we can say that ‘s’ holds a base address of a character array.
Representation | Explanation | Expression | Value |
---|---|---|---|
s[i] | First element of array | *(s + 1) | 'a' |
i[s] | First element of array | *(s + 1) | 'a' |
*(s+i) | First element of array | *(s + 1) | 'a' |
*(i+s) | First element of array | *(s + 1) | 'a' |
C Array Limitations
Limitations of Array in C Programming :
We know What is an array in C Programming. Array is very useful which stores multiple data under single name with same data type. Following are some listed limitations of Array in C Programming.
A. Static Data
- Array is Static data Structure
- Memory Allocated during Compile time.
- Once Memory is allocated at Compile Time it Cannot be Changed during Run-time
B. Can hold data belonging to same Data types
- Elements belonging to different data types cannot be stored in array because array data structure can hold data belonging to same data type.
- Example : Character and Integer values can be stored inside separate array but cannot be stored in single array
C. Inserting data in Array is Difficult
- Inserting element is very difficult because before inserting element in an array we have to create empty space by shifting other elements one position ahead.
- This operation is faster if the array size is smaller, but same operation will be more and more time consuming and non-efficient in case of array with large size.
D. Deletion Operation is difficult
- Deletion is not easy because the elements are stored in contiguous memory location.
- Like insertion operation , we have to delete element from the array and after deletion empty space will be created and thus we need to fill the space by moving elements up in the array.
E. Bound Checking
- If we specify the size of array as ‘N’ then we can access elements upto ‘N-1’ but in C if we try to access elements after ‘N-1’ i.e Nth element or N+1th element then we does not get any error message.
- Process of Checking the extreme limit of array is called Bound Checking and C does not perform Bound Checking.
- If the array range exceeds then we will get garbage value as result.
F. Shortage of Memory
- Array is Static data structure. Memory can be allocated at compile time only Thus if after executing program we need more space for storing additional information then we cannot allocate additional space at run time.
- Shortage of Memory , if we don’t know the size of memory in advance
G. Wastage of Memory
- Wastage of Memory , if array of large size is defined
Here are more some recommended readings on limitations on array.
C Accessing array
In the previous chapters we have already learnt about the basic concepts of array and how to create and initialize array. In this chapter we will be learning how we will be accessing array.
C Programming : Accessing Array
- We all know that array elements are randomly accessed using the subscript variable.
- Array can be accessed using array-name and subscript variable written inside pair of square brackets [].
Consider the below example of an array -
In this example we will be accessing array like this -
arr[3] = Third Element of Array arr[5] = Fifth Element of Array arr[8] = Eighth Element of Array
whereas elements are assigned to an array using below way -
arr[0] = 51 arr[1] = 32 arr[2] = 43 arr[3] = 24 arr[4] = 5 arr[5] = 26
Program #1 : Accessing array
#include<stdio.h> #include<conio.h> void main() { int arr[] = {51,32,43,24,5,26}; int i; for(i=0; i<=5; i++) { printf("\nElement at arr[%d] is %d",i,arr[i]); } getch(); }
Output :
Element at arr[0] is 51 Element at arr[1] is 32 Element at arr[2] is 43 Element at arr[3] is 24 Element at arr[4] is 5 Element at arr[5] is 26
How a[i] Works ?
We have following array which is declared like this -
int arr[] = { 51,32,43,24,5,26};
As we have elements in an array, so we have track of base address of an array. Below things are important to access an array -
Expression | Description | Example |
---|---|---|
arr | It returns the base address of an array | Consider 2000 |
*arr | It gives zeroth element of an array | 51 |
*(arr+0) | It also gives zeroth element of an array | 51 |
*(arr+1) | It gives first element of an array | 32 |
So whenever we tried accessing array using arr[i] then it returns an element at the location *(arr + i)
Accessing array a[i] means retrieving element from address (a + i).
We have listed out some of our observations and conclusions
arr[i] = 5 *(arr+i) = 5 *(i+arr) = 5 i[arr] = 5
all of the above notations yields same result. lets prove it using below program -
Program #2 : Accessing array
#include<stdio.h> #include<conio.h> void main() { int arr[] = {51,32,43,24,5,26}; int i; for(i=0; i<=5; i++) { printf("\n%d %d %d %d",arr[i],*(i+arr),*(arr+i),i[arr]); } getch(); }
Output :
51 51 51 51 32 32 32 32 43 43 43 43 24 24 24 24 5 5 5 5 26 26 26 26
C Initializing 2D Array
We have already studied the multidimensional array in details. In this tutorial we will be studying different ways for Initializing 2D Array in C programming
Initializing 2D Array
We have divided the concept into three different types -
Method 1 : Initializing all Elements rowwise
For initializing 2D Array we can need to assign values to each element of an array using the below syntax.
int a[3][2] = { { 1 , 4 }, { 5 , 2 }, { 6 , 5 } };
Consider the below program -
#include<stdio.h> int main() { int i, j; int a[3][2] = { { 1, 4 }, { 5, 2 }, { 6, 5 }}; for (i = 0; i < 3; i++) { for (j = 0; j < 2; j++) { printf("%d ", a[i][j]); } printf("\n"); } return 0; }
Output :
1 4 5 2 6 5
We have declared an array of size 3 X 2
, It contain overall 6 elements.
Row 1 : { 1 , 4 }, Row 2 : { 5 , 2 }, Row 3 : { 6 , 5 }
We have initialized each row independently
a[0][0] = 1 a[0][1] = 4
Method 2 : Combine and Initializing 2D Array
Initialize all Array elements but initialization is much straight forward. All values are assigned sequentially and row-wise
int a[3][2] = {1 , 4 , 5 , 2 , 6 , 5 };
Consider the below example program -
#include <stdio.h> int main() { int i, j; int a[3][2] = { 1, 4, 5, 2, 6, 5 }; for (i = 0; i < 3; i++) { for (j = 0; j < 2; j++) { printf("%d ", a[i][j]); } printf("\n"); } return 0; }
Output will be same as that of above program #1
Method 3 : Some Elements could be initialized
int a[3][2] = { { 1 }, { 5 , 2 }, { 6 } };
Now we have again going with the way 1 but we are removing some of the elements from the array. In this case we have declared and initialized 2-D array like this
#include <stdio.h> int main() { int i, j; int a[3][2] = { { 1 }, { 5, 2 }, { 6 }}; for (i = 0; i < 3; i++) { for (j = 0; j < 2; j++) { printf("%d ", a[i][j]); } printf("\n"); } return 0; }
Output :
1 0 5 2 6 0
Uninitialized elements will get default 0 value.
C Multidimensional Array
Multidimensional array
- Array having more than one subscript variable is called multidimensional array.
- Multidimensional array is also called as matrix.
Consider the Two dimensional array -
- Two Dimensional Array requires Two Subscript Variables
- Two Dimensional Array stores the values in the form of matrix.
- One Subscript Variable denotes the “Row” of a matrix.
- Another Subscript Variable denotes the “Column” of a matrix.
Declaration and Use of Two Dimensional Array :
int a[3][4];
Use :
for(i=0;i<row,i++) for(j=0;j<col,j++) { printf("%d",a[i][j]); }
Meaning of Two Dimensional Array :
- Matrix is having 3 rows ( i takes value from 0 to 2 )
- Matrix is having 4 Columns ( j takes value from 0 to 3 )
- Above Matrix 3×4 matrix will have 12 blocks having 3 rows & 4 columns.
- Name of 2-D array is ‘a‘ and each block is identified by the row & column number.
- Row number and Column Number Starts from 0.
Cell Location | Meaning |
---|---|
a[0][0] | 0th Row and 0th Column |
a[0][1] | 0th Row and 1st Column |
a[0][2] | 0th Row and 2nd Column |
a[0][3] | 0th Row and 3rd Column |
a[1][0] | 1st Row and 0th Column |
a[1][1] | 1st Row and 1st Column |
a[1][2] | 1st Row and 2nd Column |
a[1][3] | 1st Row and 3rd Column |
a[2][0] | 2nd Row and 0th Column |
a[2][1] | 2nd Row and 1st Column |
a[2][2] | 2nd Row and 2nd Column |
a[2][3] | 2nd Row and 3rd Column |
Two-Dimensional Array : Summary with Sample Example
Summary Point | Explanation |
---|---|
No of Subscript Variables Required | 2 |
Declaration | a[3][4] |
No of Rows | 3 |
No of Columns | 4 |
No of Cells | 12 |
No of for loops required to iterate | 2 |
Memory Representation
- 2-D arrays are Stored in contiguous memory location row wise.
- 3 X 3 Array is shown below in the first Diagram.
- Consider 3×3 Array is stored in Contiguous memory location which starts from 4000 .
- Array element a[0][0] will be stored at address 4000 again a[0][1] will be stored to next memory location i.e Elements stored row-wise
- After Elements of First Row are stored in appropriate memory location , elements of next row get their corresponding mem. locations.
- This is integer array so each element requires 2 bytes of memory.
Basic Memory Address Calculation :
a[0][1] = a[0][0] + Size of Data Type
Element | Memory Location |
---|---|
a[0][0] | 4000 |
a[0][1] | 4002 |
a[0][2] | 4004 |
a[1][0] | 4006 |
a[1][1] | 4008 |
a[1][2] | 4010 |
a[2][0] | 4012 |
a[2][1] | 4014 |
a[2][2] | 4016 |