C Arrays - Dynamic, 2d and Multidimensional with Examples

    0 Votes

In C programming practices, one of the frequently arising problems is to handle similar types of data and C language gives you a nice and swift way to deal this problem using arrays like other popular high level languages.

Arrays

Suppose in your company, if you have 200 employees and you want to store salaries of all 200 employees. For that, declaring 200 different variable is tedious and is impossible to maintain. So, instead of declaring 200 variables you can declare a single array of 200 sizes, where each index refers to different employees.

Declaration of Arrays

Arrays in C can be declared in following way:

<data type> <array name>[<array size>];

For example:

int employees[200];

There are some properties you need to know about arrays in C.

  • Array index starts from 0 i.e. in the above example, array indexes would be from 0 to 199 in general 0 to n-1.
  • Array allocates memory in continuous way.
  • Arrays always have fixed size i.e. you cannot change its size after its declaration.
  • Arrays can be single dimensional as well as multi-dimensional also.
Array Memory

Also Read - Top C Interview Questions and Answers for Freshers & Advanced C Interview Questions and Answers

Initialization of Single Dimensional Array

Single Dimensional Arrays in C can be initialized in the following way:

Method 1:

int rollnum[6]={5,3,32,9,2,10};

By this way, you specify the size of the array and initialize the values.

Method 2:

int rollnum[]={5,3,32,9,2,10};

You can even assign values to the array, without initializing the size of the array.

Method 3:

int rollnum[5];
int i;
for( i=0;i<5;i++ )
{
   rollnum[i] = i;
}

You can initialize the arrays this way too.

Accessing Array Elements

In C programming, you can access and operate arrays like variables in C. To access i'th element in the array you need to write as <array name>[i-1]. Since the array index starts from 0.

For example:

scanf("%d",&rollNum[3]);
/* statement to insert value in the forth element of array rollNum[]. */

scanf("%d",&rollNum[i]);
/* Statement to insert value in (i+1)th element of array rollNum[]. */
/* Because, the first element of array is rollNum[0], second is rollNum[1], ith is rollNum[i-1] and (i+1)th is rollNum[i]. */

printf("%d",rollNum[0]);
/* statement to print first element of an array. */

printf("%d",rollNum[i]);
/* statement to print (i+1)th element of an array. */

One thing you should remember is that, when you have declared roll_Number[6] array of size 6, your valid access to the array is only from 0 to 5. If you try to access any invalid index like 8, 10 etc. compiler do not throw any error, it will be throw a runtime error. Usually a program crash due to invalid memory manipulation i.e. it would cause a segmentation fault.

Multi-Dimensional Arrays

We didn't discuss these type of arrays in single dimensional arrays. C language also supports multi dimensional arrays. The number of maximum dimension you can use in your program is delimited by your compiler. The generic form of declaring a multi dimensional array is:

 [Size1][Size2][Size3]. . .[SizeN];

Also Read - Top Embedded C Interview Questions and Answers & C++ Interview Questions and Answers

Elements of Multi-Dimensional Arrays

Arrays of more than three dimensions are not often used because of the amount of memory they require. For example, a four-dimensional character array with dimensions 10,9,8,7 requires 10 * 9 * 8 * 7 or 5040 bytes.

If it is an integer array, then it would take 4 times the memory. So you can imagine that how big the memory becomes.

In multidimensional arrays, computer takes more time to compute each index. This means that accessing an element in a multidimensional array can be slower than accessing an element in a single-dimensional array.

It is good to have a look at how the elements in multidimensional array stored in memory. For simplicity, take a three dimensional array. As you can see earlier, arrays are stored in continuous way in memory. For a three dimensional array, you can imagine the memory allocation like a Rubik’s cube. Memories are allocated from 1'st row followed by 2'nd level and so on. In this way memories are allocated one after another.

Accessing and Initialization of Two Dimensional Array

The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional array is essentially, an array of one-dimensional arrays. To declare a two-dimensional integer array "S" of size 10,20, you would write.

int s[10][20];

Two-dimensional arrays are stored in a row-column matrix, where the first index indicates the row and the second indicates the column. This means that the rightmost index changes more quickly than the leftmost when accessing the elements in the array in the order in which they are actually stored in memory.

Suppose, you want to access element located at 3'rd row and 5'th column of the two dimensional array "S", store the value in a integer variable var then the statement would be like this :

int var =  s[2][4]; /* As Array index start from 0, 2 indicates 3'rd Row and 4 indicates 5'th Column*/

Passing Arrays To Functions

Whenever we need to pass a list of elements as parameter to the function, it is preferred to do that using an array. But how can we pass an array as parameter? Let’s see how to do it.

Fundamentally, there is one way to do it. But, syntactically three ways to do it. You can pass entire array to a function using pointer. Usually, pointer variable is used to store memory addresses, so you can pass the location of first element of your array to the function using the pointer.

Usually, when you call a function from your current function then the current function is called Calling Function and the function you are calling is called Called Function.

When you are passing the array to a function using pointer, you have to pass its size also. Otherwise, if you do some invalid access of array in the called function, it could be a serious problem! So it is best practice to pass the size of array also.

The syntax of the three ways are given below:

Method 1:

<return type> <Function name>(<data type> *<pointer variable name>)

{
	/* Your Function Body Here */
	…..............................
}

Example :
int function ( int *my_array, int size)  /* size indicating my_array size */
{
	int i;
	for (i=0;i<size;i++)
		printf(“%d ”,my_array[i]);
}

Method 2:

<return type> <Function name>(<data type> <pointer variable name>[])

{
	/* Your Function Body Here */
	…..............................
}

Example :
int function ( int my_array[], int size)  /* size indicating my_array size */
{
int i;
for (i=0;i<size;i++)
	printf(“%d ”,my_array[i]);
}

Method 3:

<return type> <Function name>(<data type> <array name>[<array size>])

{
	/* Your Function Body Here */
	…..............................
}

Example :
int function ( int my_array[10])  /* Here 10 indicates my_array size */
{
	int i;
	for (i=0;i<10;i++)
		printf(“%d ”,my_array[i]);
}

You can see that, there is a difference in syntax but all are actually passing the pointer. You can test it by modifying the the values of array in called function and printing the array in calling function after calling the called function. You will see that the values has been modified in all the three syntax given above.

Planning to do an MBA?
A quick all-in-one MBA entry manual for MBA Aspirants. Book covers
  • Possible MBA Tests & Exam Preparation
  • Tips to choose right MBA Program
  • Essay, Resume & Letter of Recommendation
  • MBA Interview Preparation
  • MBA Financial Planning
Price - 6.99$
 

Popular Videos

How to speak to people

How to speak so that people want to listen.

Got a tip or Question?
Let us know

Related Articles

C Overview and Basic Syntax
Data Types in C Language
C Qualifiers - Constant and Volatile type Qualifier
C Type Casting with examples - float to int / int to char / int to long
C Constants and Literals
C Operators - Arithmetic, Assignment, Relational and Logical
C Operators - Bitwise Operators and Conditional Operators
C Operator Precedence and Associativity Table with Examples
C Input and Output Statements
C Format Specifiers for printf and scanf
C Decision Making Control Structures - 'if', 'if - else', nested 'if', 'switch'
Loops in C - for, while and do...while Loops
C 'break', 'continue' and 'goto' Statements to Control Program Flow
C Preprocessor Directives and Macros
C Functions Tutorial with Examples
C Strings - Internal Working and Functions with example
C Pointers basics explained with examples
Structures in C Programming with Example
Unions in c programming with example
C Storage Class Specifiers - auto, register, static and extern