Arrays in C (definition and initialization)

Array is a data type to store similar types of elements in contiguous memory segments, pictorial representation of arrays is as shown below.

An integer array “a” of size 7 starts at address 1000.

Above array of 7 integers represents with variable “a” is {1, 5, 1, 2, 6, 8, 3} starts at address 1000. In a 32bit machine size of an integer value is 4bytes (32bits). As this array size is 7, so it takes a total memory of 28bytes which starts from address location 1000 to 1028.

C Array Definition

In C Programming, to define an array we use an array brackets (i.e., “[]”) with a constant integer value size inside the bracket.

<data type> <variable name>[<constant size>];

int a[7];    // Definition of an integer array of size 7.

Here, “a” represents a pointer to the address of array (1000 in our example case). Let’s see a sample program which defines the array and prints the address of it.

#include <stdio.h>

int main()
{
    int a[7];
    printf("%x\n", a);
    return 0;
}
// Output
e2b48a70

In this example, the array starts at address e2b48a70. This array address is the same as the first item address which is also represented as &a[0].

Let’s print the second item address and see what it prints.

int main()
{
    int a[7];
    printf("%x\n", a);      // Prints first item address.
    printf("%x\n", &a[0]);  // Prints first item address.
    printf("%x\n", &a[1]);  // Print second item address.
    return 0;
}
// Output
ece89a70
ece89a70
ece89a74

As I am running this program in a 32bit machine, the second item address is 4bytes more than the first item address as showing in the program output.

C Array Initialisation

There are multiple ways of initializing an array in C programming, whereas here we are going to initialize it using a for loop as showing in the below program.

int main()
{
    int a[7];
    int i;
    printf("%x\n", a);
    printf("%x\n", &a[0]);
    printf("%x\n", &a[1]);
    // Initialising the array with values 1...7
    for(i=0; i<7; i++) {
        a[i] = i+1;
    }
    return 0;
}

Here we are initializing the array with values 1 to 7. To access the values of an array we use the same square brackets with an index value which is less than or equal to array size.

These are some basics of C Arrays. To have more details on arrays, I want readers to add whatever they knows about arrays in comments below to make this article more useful to others. Happy Learning!.

See more:
http://rjp.b44.myftpupload.com/arrays/
http://rjp.b44.myftpupload.com/search-an-integer-in-sorted-rotated-integer-array/