C Arrays Basics Explained with 13 Examples

by Himanshu Arora on December 12, 2011

This article is part of our on-going C programming series.

There are times while writing C code, you may want to store multiple items of same type as contiguous bytes in memory so that searching and sorting of items becomes easy. For example:

  1. Storing a string that contains series of characters. Like storing a name in memory.
  2. Storing multiple strings. Like storing multiple names.

C programming language provides the concept of arrays to help you with these scenarios.

1. What is an Array?

An array is a collection of same type of elements which are sheltered under a common name.

An array can be visualised as a row in a table, whose each successive block can be thought of as memory bytes containing one element. Look at the figure below :

An Array of four elements:

+===================================================+
| elem1     |  elem2      | elem3      | elem4      |
+===================================================+

The number of 8 bit bytes that each element occupies depends on the type of array. If type of array is ‘char’ then it means the array stores character elements. Since each character occupies one byte so elements of a character array occupy one byte each.

2. How to Define an Array?

An array is defined as following :

<type-of-array> <name-of-array> [<number of elements in array>];
  • type-of-array: It is the type of elements that an array stores. If array stores character elements then type of array is ‘char’. If array stores integer elements then type of array is ‘int’. Besides these native types, if type of elements in array is structure objects then type of array becomes the structure.
  • name-of-array: This is the name that is given to array. It can be any string but it is usually suggested that some can of standard should be followed while naming arrays. At least the name should be in context with what is being stored in the array.
  • [number of elements]: This value in subscripts [] indicates the number of elements the array stores.

For example, an array of five characters can be defined as :

char arr[5];

3. How to Initialize an Array?

An array can be initialized in many ways as shown in the code-snippets below.

Initializing each element separately. For example :

int arr[10];
int i = 0;
for(i=0;i<sizeof(arr);i++) 
{ 
  arr[i] = i; // Initializing each element seperately 
} 

Initializing array at the time of declaration. For example :

int arr[] = {'1','2','3','4','5'};

In the above example an array of five integers is declared. Note that since we are initializing at the time of declaration so there is no need to mention any value in the subscripts []. The size will automatically be calculated from the number of values. In this case, the size will be 5.

Initializing array with a string (Method 1):

Strings in C language are nothing but a series of characters followed by a null byte. So to store a string, we need an array of characters followed by a null byte. This makes the initialization of strings a bit different. Let us take a look :

Since strings are nothing but a series of characters so the array containing a string will be containing characters

char arr[] = {'c','o','d','e','\0'};

In the above declaration/initialization, we have initialized array with a series of character followed by a ‘\0′ (null) byte. The null byte is required as a terminating byte when string is read as a whole.

Initializing array with a string (Method 2):

char arr[] = "code";

Here we neither require to explicitly wrap single quotes around each character nor write a null character. The double quotes do the trick for us.

4. Accessing Values in an Array

Now we know how to declare and initialize an array. Lets understand, how to access array elements. An array element is accessed as :

int arr[10];
int i = 0;
for(i=0;i<sizeof(arr);i++) 
{ 
  arr[i] = i; // Initializing each element separately 
} 
int j = arr[5]; // Accessing the 6th element of integer array arr and assigning its value to integer 'j'. 

As we can see above, the 6th element of array is accessed as ‘arr[5]‘.

Note that for an array declared as int arr[5]. The five values are represented as: arr[0] arr[1] arr[2] arr[3] arr[4] and not arr[1] arr[2] arr[3] arr[4] arr[5]

The first element of array always has a subscript of ’0′

5. Array of Structures

The following program gives a brief idea of how to declare, initialize and use array of structures.

#include<stdio.h>

struct st{
    int a;
    char c;
}; 

int main()
{
    struct st st_arr[3]; // Declare an array of 3 structure objects 

    struct st st_obj0; // first structure object
    st_obj0.a = 0;
    st_obj0.c = 'a'; 

    struct st st_obj1; //Second structure object
    st_obj1.a = 1;
    st_obj1.c = 'b'; 

    struct st st_obj2; // Third structure object
    st_obj2.a = 2;
    st_obj2.c = 'c'; 

    st_arr[0] = st_obj0; // Initializing first element of array with first structure object
    st_arr[1] = st_obj1; // Initializing second element of array with second structure object
    st_arr[2] = st_obj2; // Initializing third element of array with third structure object 

    printf("\n First Element of array has values of a = [%d] and c = [%c]\n", st_arr[0].a, st_arr[0].c);
    printf("\n Second Element of array has values of a = [%d] and c = [%c]\n", st_arr[1].a, st_arr[1].c);
    printf("\n Third Element of array has values of a = [%d] and c = [%c]\n", st_arr[2].a, st_arr[2].c); 

    return 0;
}

The output of the above program comes out to be :

$ ./strucarr 

 First Element of array has values of a = [0] and c = [a] 

 Second Element of array has values of a = [1] and c = [b] 

 Third Element of array has values of a = [2] and c = [c]

6. Array of Char Pointers

The following program gives a brief Idea of how to declare an array of char pointers :

#include<stdio.h>

int main()
{
    // Declaring/Initializing three characters pointers
    char *ptr1 = "Himanshu";
    char *ptr2 = "Arora";
    char *ptr3 = "TheGeekStuff"; 

    //Declaring an array of 3 char pointers
    char* arr[3]; 

    // Initializing the array with values
    arr[0] = ptr1;
    arr[1] = ptr2;
    arr[2] = ptr3; 

    //Printing the values stored in array
    printf("\n [%s]\n", arr[0]);
    printf("\n [%s]\n", arr[1]);
    printf("\n [%s]\n", arr[2]); 

    return 0;
}

The output of the above program is :

$ ./charptrarr 

 [Himanshu] 

 [Arora] 

 [TheGeekStuff]

7. Pointer to Arrays

Pointers in C Programming language is very powerful. Combining pointers with arrays can be very helpful in certain situations.

As to any kind of data type, we can have pointers to arrays also. A pointer to array is declared as :

<data type> (*<name of ptr>)[<an integer>]

For example :

int(*ptr)[5];

The above example declares a pointer ptr to an array of 5 integers.

Lets look at a small program for demonstrating this :

#include<stdio.h>

int main(void)
{
    char arr[3];
    char(*ptr)[3]; 

    arr[0] = 'a';
    arr[1] = 'b';
    arr[2] = 'c'; 

    ptr = &arr; 

    return 0;
}

In the above program, we declared and initialized an array ‘arr’ and then declared a pointer ‘ptr’ to an array of 3 characters. Then we initialized ptr with the address of array ‘arr’.

8. Static vs Dynamic Arrays

Static arrays are the ones that reside on stack. Like :

char arr[10];

Dynamic arrays is a popular name given to a series of bytes allocated on heap. this is achieved through malloc() function. Like :

char *ptr = (char*)malloc(10);

The above line allocates a memory of 10 bytes on heap and we have taken the starting address of this series of bytes in a character pointer ptr.

Static arrays are used when we know the amount of bytes in array at compile time while the dynamic array is used where we come to know about the size on run time.

9. Decomposing Array into Pointers

Internally, arrays aren’t treated specially, they are decomposed into pointers and operated there-on. For example an array like :

char arr[10];

When accessed like :

arr[4] = 'e';

is decomposed as :

*(arr + 4) = 'e'

So we see above that the same old pointers techniques are used while accessing array elements.

10. Character Arrays and Strings

Mostly new programmers get confused between character arrays and strings. Well, there is a very thin line between the two. This thin line only comprises of a null character ‘\0′ . If this is present after a series of characters in an array, then that array becomes a string.
This is an array:

char arr[] = {'a', 'b', 'c'};

This is a string:

char arr[] = {'a', 'b', 'c', '\0'};

Note : A string can be printed through %s format specifier in printf() while an printing an array through %s specifier in printf() is a wrong practice.

11. Bi-dimensional and Multi-dimensional Arrays

The type of array we discussed until now is single dimensional arrays. As we see earlier, we can store a set of characters or a string in a single dimensional array. What if we want to store multiple strings in an array. Well, that wont be possible using single dimensional arrays. We need to use bi-dimensional arrays in this case. Something like :

char arr[5][10];

The above declaration can be thought of as 5 rows and 10 columns. Where each row may contain a different name and columns may limit the number of characters in the name. So we can store 5 different names with max length of 10 characters each.
Similarly, what if we want to store different names and their corresponding addresses also. Well this requirement cannot be catered even by bi-dimensional arrays. In this case we need tri-dimensional (or multi-dimensional in general) arrays. So we need something like :

char arr[5][10][50];

So we can have 5 names with max capacity of 10 characters for names and 50 characters for corresponding addresses.
Since this is an advanced topic, So we won’t go into practical details here.

12. A Simple C Program using Arrays

Consider this simple program that copies a string into an array and then changes one of its characters :

#include<stdio.h>
#include<string.h>

int main(void)
{
    char arr[4];// for accommodating 3 characters and one null '\0' byte.
    char *ptr = "abc"; //a string containing 'a', 'b', 'c', '\0' 

    memset(arr, '\0', sizeof(arr)); //reset all the bytes so that none of the byte contains any junk value
    strncpy(arr,ptr,sizeof("abc")); // Copy the string "abc" into the array arr 

    printf("\n %s \n",arr); //print the array as string 

    arr[0] = 'p'; // change the first character in the array 

    printf("\n %s \n",arr);//again print the array as string
    return 0;
}

I think the program is self explanatory as I have added plenty of comments. The output of the above program is :

$ ./array_pointer 

 abc 

 pbc

So we see that we successfully copied the string into array and then changed the first character in the array.

13. No Array Bound Check in a C Program

What is array bound check? Well this is the check for boundaries of array declared. For example :

char arr[5];

The above array ‘arr’ consumes 5 bytes on stack and through code we can access these bytes using :

arr[0], arr[1], arr[2], arr[3], arr[4]

Now, C provides open power to the programmer to write any index value in [] of an array. This is where we say that no array bound check is there in C. SO, misusing this power, we can access arr[-1] and also arr[6] or any other illegal location. Since these bytes are on stack, so by doing this we end up messing with other variables on stack. Consider the following example :

#include<stdio.h>

unsigned int count = 1; 

int main(void)
{
    int b = 10;
    int a[3];
    a[0] = 1;
    a[1] = 2;
    a[2] = 3; 

    printf("\n b = %d \n",b);
    a[3] = 12;
    printf("\n b = %d \n",b); 

    return 0;
}

In the above example, we have declared an array of 3 integers but try to access the location arr[3] (which is illegal but doable in C) and change the value kept there.

But, we end up messing with the value of variable ‘b’. Cant believe it?, check the following output . We see that value of b changes from 10 to 12.

$ ./stk 

 b = 10 

 b = 12

Linux Sysadmin Course Linux provides several powerful administrative tools and utilities which will help you to manage your systems effectively. If you don’t know what these tools are and how to use them, you could be spending lot of time trying to perform even the basic administrative tasks. The focus of this course is to help you understand system administration tools, which will help you to become an effective Linux system administrator.
Get the Linux Sysadmin Course Now!

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

{ 44 comments… read them below or add one }

1 Celaleddin December 12, 2011 at 6:42 am

something wrong in “4. Accessing Values in an Array”
for(i=0;i

2 Cas December 12, 2011 at 8:27 am

The code blocks in 3. and 4. are incomplete.

3 Ramesh Natarajan December 12, 2011 at 9:07 am

@Celaleddin, @Cas,

Thanks for pointing it out. It is fixed.

4 Dave Ariens December 12, 2011 at 9:22 am

@Cas – Correction: The code blocks in 3 and 4 do not render properly in FF

5 Adam December 12, 2011 at 12:09 pm

The last line of the code block for example 4 either has an incorrect array index or the comment is incorrect.
“int j = arr[5]; // Accessing the 5th element of integer array arr and assigning its value to integer ‘j’.”
If the index is wrong it should be ‘int j = arr[4];’ if your trying to access the 5th element or if you really want the ‘int j = arr[5];’ (5th index) the comment should read ‘// Accessing the 6th element…’

6 Jero Granizo December 19, 2011 at 1:57 am

The calculation of the length of the array is wrong. The sizeof operator returns the size in bytes of the operand. To get the length of an array we have to divide by the size of an item. Like this:

for(i=0;i<sizeof(arr)/sizeof(arr[0]);i++)

7 Himanshu December 21, 2011 at 3:45 am

My sincere apologies for some small mistakes in this article. I appreciate the efforts of the members who pointed out at the loop holes. I’ll make sure that these type of mistakes will not happen in any of my future articles.

8 DarkVenger March 27, 2012 at 9:54 am

@ Jero Granizo, just to leave here a little bit more information.

I would not call it incorrect but rather inaccurate, or even dangerous.
The sizeof function computes the size of a datatype, as in the number of bytes. So the author is assuming the int variable to have 1 byte of size, which may be correct. An unsigned char type declaration would be a more safer choice.
But as Jero Granizo shows, the most portable/compatible solution is dividing.

9 Andrei Agulescu August 26, 2012 at 11:39 am

The following code has an error

int arr[10];
int i;
for(i=0;i<sizeof(arr);i++)
{
arr[i] = i; // Initializing each element seperately
}

The size of the array is given by sizeof(arr)/sizeof(int)
Using just sizeof(arr) will yield 10*4=40 and the for will iterate from 0 to 39 causing an memory access violation!

10 sharma mahendra September 12, 2012 at 11:10 am

hi.. my name is sharma mahendra i want to laern two and multy dimenttioanl array…

please give me example in array in two and multy dimentioanl …array delete and update data…

11 P.BALAMURUGAN September 22, 2012 at 10:55 am

hai i am balamurugan now i am analysing the array concept.
i want know the various application in an array………

12 rajjan October 5, 2012 at 2:48 am

main() { int[2][2][2]={{10,2,3,4}},{5,6,7,8}}; int *p,*q; p=&a[2][2][2]; *q=***a; printf(“%d—-%d”,*p,*q); getch(); } what is the output and exlain the output

13 Rajesh November 6, 2012 at 11:47 pm

Refrring to the tri-dimensional array example you have given-
char arr[5][10][50];
I think the explanation is wrong. There will be a total of 5x10x50 characters(2500 chars).
So if you assume 5 names each with max of 10 chars, you will have 490 chars for address for each of the 5 names.

14 V.ABINAYA November 17, 2012 at 11:37 pm

Please help me to do programme on matrix multiplication,upper triangular matrix and transpose

15 jasmin December 19, 2012 at 6:33 am

plz,give me all array example

16 Dan V December 20, 2012 at 5:47 pm

Pointer to Array’s saved me. Working with GLib to make a list of arrays. Only way I could figure out how to access them was with:
int (a*)[] = list->data;
int ele = (*a)[0];

17 Mukesh k jat January 2, 2013 at 9:32 pm

please give me 2 dimensional array

18 sheena marie nolasco January 11, 2013 at 1:14 am

can i ask a favor .. give me some of examples in one problem of link list and array having flow chart ,pseuducode and simulation in each. :) tnx

19 Prasad January 16, 2013 at 10:44 am

Good article

20 nathaniel January 17, 2013 at 1:27 am

hey guyz.. good day! this is urgent.. i need this project before january 23,2013. hope u can help me..!! thanks in advanced!!
output like this:

Enter number of subject: //max subject 10 //example 3

Enter 1 subject: math
Enter 2 subject: science
Enter 3 subject: english

Enter grade in math: //students grade. //ex. 80
Enter grade in science: 85
Enter grade in english: 90

math: 80
science: 85
english: 90
sum = 225/3
average is: 85

The highest suject is _________ which is ______.
//so The highest suject is ENGLISH which is 90.

21 soumen dofadar January 24, 2013 at 11:38 pm

really helpfull…

22 DuskoKoscica January 25, 2013 at 3:51 am

Ok hi, I have been wondering around and I have summbled on this statement>

What is an Array?
An array is a collection of same type of elements which are sheltered under a common name.

The question arise from this one. Have you ever, ever, tried to use union, and records with array. Your statement don’t make any sens.
After you have tried things, i had suggested you, there would be different opinion in your mind.
Yes, tehnickly they take enough space for the biggest data, but they all are not of same tipe…
Before saying something like that, you have to see the bigger picture. Yes, I have red many books, and wrote many programs… and so on… but the statement is not correct. That is my point of view.
If necessery, i will provide small program to colaborate my statements…
Ok have nice day, or night, whatever apply to tyo

23 Sikandar Wali Bazi February 12, 2013 at 12:27 pm

oh well so so nice info thnx for sharing…

24 tamil March 12, 2013 at 6:22 am

Hai frnds for me one doubt…
In array we are using subscript value that is char a[5], here 5 is used to get 5 elements(aaaaa) or 5 strings(aaaaa,bbb,ccc,dd,eee)

25 chawla April 24, 2013 at 12:45 pm

thank u soooo much now i was cleared in array concept..

26 Anonymous May 14, 2013 at 3:13 pm

for 3. Initializing, the upper limit of i should be sizeof(arr)/sizeof(int)

27 saad July 21, 2013 at 9:52 am

hy i m saad , plz define arry with any good example

28 ORCHI September 16, 2013 at 11:51 pm

#include
#include
int main()
{
int p;
printf(“Enter the value of parameter: “);
scanf(“%d”,&p);

int ar[12][12];
int i=0;
int j=0;

for(i=0;i<12;i++)
{ for(j=0;j<12;j++)
{ printf("\nEnter the value of %d row, %d column : ",i+1,j+1);
scanf("%d",&ar[i][j]);
}

}

for(i=0;i<12;i++)
{ for( j=0;j=p)
{ ar[i][j]=1;
}

else ar[i][j]=0;
}
}
printf(“\n\n\n\n”);
for(i=0;i<12;i++)
{ for(j=0;j<12;j++)
{ printf(" %d",ar[i][j]);
}
printf("\n");
}
getch();
return 0;
}
when i am running this program in DEVC++
it is not taking tha value of the array. it is giving its own values .

29 Dhivya September 17, 2013 at 1:01 pm

@Tamil, char[5] prints only 5 characters. that is [A,A,A,A,A].

30 Thiranjaya September 20, 2013 at 5:47 pm

It helps me a lot, thanks.

31 E. Priyanga October 14, 2013 at 11:13 am

write a program to merge two arrays

32 dc October 16, 2013 at 10:18 am

Hi I am trying to draw a roulette table in c. I have used lots of individual filled arc functions to make up the circle…….(see below) I won’t put the full code unless you want it but my question is, How do I use an array to make my code tidy and faster? I am new to code and I might have the wrong idea completely if so point me in the right direction or I can send full code to explain better. Also I can’t work out how to put numbers around the arc like a roulette wheel. I will need to animate it in time and place bets/selections. This is just a c programming project so not real betting just an exercise in learning c.

Thank you.

gdImageFilledArc(gdImage, 400, 400, 790, 790, 360/37, 2*360/37, red, gdArc);
gdImageFilledArc(gdImage, 400, 400, 790, 790, 2*360/37, 3*360/37, black, gdArc);
gdImageFilledArc(gdImage, 400, 400, 790, 790, 3*360/37, 4*360/37, red, gdArc);
gdImageFilledArc(gdImage, 400, 400, 790, 790, 4*360/37, 5*360/37, black, gdArc);
gdImageFilledArc(gdImage, 400, 400, 790, 790, 5*360/37, 6*360/37, red, gdArc);
gdImageFilledArc(gdImage, 400, 400, 790, 790, 6*360/37, 7*360/37, black, gdArc);
gdImageFilledArc(gdImage, 400, 400, 790, 790, 7*360/37, 8*360/37, red, gdArc);
gdImageFilledArc(gdImage, 400, 400, 790, 790, 8*360/37, 9*360/37, black, gdArc);
gdImageFilledArc(gdImage, 400, 400, 790, 790, 9*360/37, 10*360/37, red, gdArc);

33 Maitreyi October 21, 2013 at 7:06 am

given examples are to good…….thank u sir

34 Anonymous November 8, 2013 at 1:33 am

8. WAP to print octal equivalent of any decimal number.

35 vstoianov November 14, 2013 at 1:15 am

Point 3 is not completely correct.
In this example:
int arr[10];
int i = 0;
for(i=0;i<sizeof(arr);i++)
{
arr[i] = i; // that's an assignment of value!!! it is not an initialization!!!
}

36 redditguy December 15, 2013 at 3:35 pm

Example three is incorrect!

int arr[] = {1,0,1,etc..}

remove the quotes around the numbers otherwise it will be using the ascii values instead! 48,49

also,

for(i=0;i<sizeof(arr);i++) is wrong.

should be: for(i=0;i < sizeof(arr)/sizeof(arr[0]);i++)

37 Safi December 22, 2013 at 11:00 am

I want simple methord of c

38 yash kothari January 28, 2014 at 8:41 am

Write a C program to accept 10 numbers and count total number of even numbers & odd numbers using array.

39 Rupsi Singh February 14, 2014 at 7:18 am

Hii,I always confuse about pointer to an array but it helps me alot!

40 anushka February 18, 2014 at 9:02 am

thnx alot

41 saima June 1, 2014 at 11:21 pm

define Arrays Topic

42 abhi July 3, 2014 at 2:27 am

5[ch] prg in array tel me about that

43 pooja August 1, 2014 at 8:46 pm

Coding for binary search of array using simple Clanguage

44 Radhika Baghel October 12, 2014 at 7:29 pm

Plz give some small array programs in c

Leave a Comment

Previous post:

Next post: