Arrays in any programming language is one of the “power tools” you can use to organize data of same type. On the positive side elements of an array can be accessed in constant time because of the maintained indexes. On the downside array is fixed size and taking space after each other in memory which is not to efficient.
Array declaration and accessing elements works as in other languages, with an example:

   int myInts_1[5];//declaring a 5 element int array without initialization
   int myInts_2[] = {0, 1, 2, 3, 4};//with initialization this could be done as {0} to init all to 0
   int my2dArr[2][3] = {
                       };//this is a 2d array with 3 elements on each level 

   //accessing the elements   
   myInts_1[0] = myInts_2[0];
   printf("%d", &my2dArr[1][1]);//this would print 5

The first element of an array is at 0 and the last element is at the array size-1. In newer languages there are all sorts of ways to write a loop which does “touch” all elements, like foearch. Implementing the same into c is tricky. An easy way to go around the problem of not knowing the array size is declare a constant array size an loop until that size -1. If for other reasons you cant implement constants, dividing the size of an array with element 1 gives the size. There is an advanced way of implementing foreach with macro which is really limited to a type or to a structure/union(can’t be used randomly for any type) so I am not going to cover it.
A basic example:

    unsigned int n = sizeof(theArray)/sizeof(theArray[0]);//n will hold the size of the array

Array in c can be combined with pointer to access the elements in a less memory consuming way. This could be useful when passing large arrays, where pointer is taking way less memory as passing a copy of all elements. Keep in mind that passing pointer as parameter modifies the original value where the pointer points to, inside the function.

Share This