Users Online

· Guests Online: 5

· Members Online: 0

· Total Members: 185
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

FAQ: C Arrays

FAQ (Frequently Asked Questions) >C Arrays
01 What is the Difference Between Declaration of an Array and a Variable in C02 Explain One-Dimensional Array in C with Examples03 Explain Array Subscripts in C Language with Examples04 Can we Use Pointer for Subscript to Access an Array in C Programming?
05 Is Pointer more Efficient than Using Subscript to Access an Array in C Programming?06 Are Expressions arrays[i] and i[arrays] same?07 Explain Array in C with Examples08 Are Pointers and Arrays Same in C?
09 Can One-Dimensional Arrays be passed as Function Arguments in C Language?10 What do we mean by Static and Automatic Initialization of an Array in C?11 What is Incomplete Initialization in C Programming?12 Explain Character Array Initialization in C with Examples
13 What is a Multidimensional Array in C Programming?14 Explain Pointer to Array in C with Examples15 Can Multidimensional Arrays be Passed as Function Arguments in C?16 Explain Array of Pointers in C with Examples
17 Size of an Array using sizeof Operator OR strlen() Function in C Language
01 What is the Difference Between Declaration of an Array and a Variable in C
Question: What is the Difference Between Declaration of an Array and a variable in C?
Answer: Let’s try to understand following declarations,

int main(void)
{
int x; /* x is declared as integer */
char initial; /* initial is a character */
int num[10]; /* num is an array of 10 integers */
char msg[10]; /* msg is an array of 10 characters */

return 0;
}
Let’s unravel how these declarations are internally interpreted. When we compile the program containing these statements, compiler compiles the program instruction by instruction. When it reaches the first statement,

int x;
it allocates a block of 4 bytes of memory for ‘x’ because it’s of type int on Linux System. It recognises this block by address of its first byte i.e. integer x is located at this address in the memory, though, we name this block as ‘x’.

When compiler reaches the next statement:

char initial;
it allocates just one byte of memory and recognises this as character ‘initial’. Individual variables like ‘x’, initial etc. are also called “Scalar variables”.

Now, when compiler reaches the statement:

int num[10];

it sets aside a block of 40 bytes for 10 integers specified by subscript and creates the name ‘num’ and sets this to the beginning of the block. This declaration is also called as vector i.e. an array of 10 integers. Next statement:

char msg[10];
when compiled, creates an array ‘msg’ of enough size to hold 10 characters.

Remember that compiler allocates memory to a scalar variable according to its type on a given system.
Top
02 Explain One-Dimensional Array in C with Examples
This C Tutorial Explains One-Dimensional Array in C and its initialization with Example(s).
An array with just one dimension is called one-dimensional array. Dimension of an array is specified by a pair of square brackets called subscript immediately after the name of array. For example,

int new[n]; /* new, a one dimensional array */
Expression ‘n’ in square brackets specifies no. of elements in the array ‘new’ meaning that new contains ‘n’ integers.

int champions[12][10]; /* champions, an array, have two dimensions */
An array is allocated block of memory for the specified no. of elements in contiguous or continuous locations by the compiler. For example,

int num[10]; /* allocates enough memory to hold 10 integers */


Let’s see what happens when declaration is as below:

int count[]; /* no. of elements not specified! */
Certainly, this is an error! How would compiler know about what amount of memory to allocate? <>bSo, specifying no. of elements is must unless you declare the array and initialize it. For example:

int mugs[] = {1,2,3,4,5,6,7,8,9,10};
/* no. of elements not specified but mugs[] initialized */
Remember, specifying elements isn’t needed during initialization of an array changes its size most often.<\b> O key! we consider one more example:

int students[5] = {35, 44, 55, 80, 40, 20};
/* more elements than size? */
Well! We can’t pack 6 integers into an array of 5 integers. This is an error! What about


int hours[10] = {1,2,3,4,5}; /* less no. of elements than size */
When during declaration and initialization of an array with specified size, if no. of initializers in the list is less than size specified, given initializers are assigned to successive locations beginning with index ZERO and rest of uninitialized locations are each automatically assigned with value ZERO.

The above initialization of array hours[10] can be though of as the successive assignments below,

hours[0] = 1;
hours[1] = 2;
hours[2] = 3;
hours[3] = 4;
hours[4] = 5;

hours[5] = 0;
hours[6] = 0;
hours[7] = 0;
hours[8] = 0;
hours[9] = 0;
hours[10] = 0;
Top
03 Explain Array Subscripts in C Language with Examples
This C Tutorial Explains Subscript used in Arrays in C Language with Example(s).
Let’s start with what we already know by considering declaration of a pointer-to-integer given below,

int banks = 100; /* banks, an integer */
int *pi = &banks; /* pointer 'pi' points to integer 'banks' */

printf("value of banks is %3d\n", banks);
printf("value of banks, using ptr-to-int, pi, is %3d\n", *pi);
Here, we performed indirection on pointer-to-integer ‘pi’ to access the location ‘pi’ is pointing to and that is integer banks, reading value there as R-Value or writing new value over there as L-Value.

Let’s, now, try a one-dimensional array, for example,

int bottles[5] = {23, 34, 11, 56, 12};
This time we analyse every aspect of declaration and initialization of array bottles[5]. At first, block of memory is allocated to the array before initialization begins. There are 5 initializers in the list which are assigned one each into locations beginning with indices 0 through 4. This initialization takes place as below,

bottles[0] = 23;
bottles[1] = 34;
bottles[2] = 11;
bottles[3] = 56;
bottles[4] = 12;
Now, array ‘bottles[5]’ is initialized with values from the initializer’s list. Let’s now come to see how can we access the values in the array. We consider, for example, first element of the array,

bottles[0]; /* what's this? */
Remember that name of an array is a Pointer Constant i.e. some constant address in memory i.e. this can’t be changed or modified so is constant! And this pointer constant points to the beginning of the array, more clearly to the first element of the array which is ‘bottles[0]’. As we know we dereference the pointer-to-integer to access the integer indirectly using the pointer. Similarly, to access the value, an integer, at the location ‘bottles[0]’ pointed to by ‘bottles’, ‘bottles’ being a pointer constant, we need to perform indirection on the pointer constant i.e. on ‘bottles[0]’. Here, we have subscript operator, ‘[]’, which aside from having higher precedence than indirection operator (*) is same as indirection operator. So, subscripts in arrays perform indirection or dereferencing. This indirection as in pointers causes value to read from the pointed to location as R-Value or write new value there as L-Value.

Therefore, expression,

bottles[0]


reads value 23. Now, we move over to next location in the array bottles

bottles[1] /* what's this" */
As we know an integer occupies 4 bytes on Linux System and array is allocated block of memory in continuous locations, we compute the address for 2nd element

bottles[1]
in order to evaluate its value. Let’s see how? Firstly, name of array, bottles, gives the address of first element, let’s say,

1000
then index 1, multiplying by 4, is scaled to the size of integer because bottles is an array of integers.

1 * 4
This value is added to 1000, where array points to in memory.

1000 + 1 * 4
and then subscript performs indirection on the resultant address value, here 1004 to access the value at pointed to location. This process can be repeated for other elements with their specified index value in the array.

Because subscript ‘[]’ operator performs the same function as indirection operator ‘*’ with arrays, we can substitute the expression:


bottles[0];
with

*(bottles + 0);
which can be reduced to

*(bottles);
meaning that when indirection is performed on array name this results in value of the first element.

Similarly, we can write

bottles[1] as *(bottles + 1)
and so on.
Top
04 Can we Use Pointer for Subscript to Access an Array in C Programming?
Question: Can we Use Pointer for Subscript to Access an Array in C Programming?
Answer: Subscript operator ‘[]’ have higher precedence than indirection operator ‘*’, but in fact, both are same. Let’s see an example,

int max[5] = {1,2,3,4,5}; /* max[5] is an array of 5 integers */
Well! In order to access elements of array ‘max[]’ using pointer, we must know type of array ‘max[]’ so we can declare and initialize pointer of same type to use it to access array ‘max[]’. So, what’s the type of array ‘max[]’? ‘max[5]’ is an array of 5 something which happen to be 5 integers. Address of first integer ‘max[0]’, let’s say,

1000
which is calculated as,

1000 + 0 * 4 /* type 'int' takes 4 bytes */
address of 2nd element ‘max[1]’ is calcuated as,

1000 + 1 * 4 /* 1000 is the base address of the array 'max[]' */

and so on. Since each address points to an integer, therefore type of array is pointer-to-integer. So,

int *pi; /* 'pi' is pointer to type int */
and its initialization

pi = array;
/* value of array, pointer constant, is copied into pointer 'pi' */
allows us to access the elements of array ‘max[]’. Now, ‘pi’ points to the first element, ‘max[0]’, of array. On performing indirection on the ‘pi’, value at the location pointed to by pi is obtained. For example,

*pi; /* value of 'max[0]' is obtained */
Next, how can we obtain values of successive elements of array ‘max[]’? We’re very well familiar with pointer arithmetic and here we would implement it to learn how simple it’s to access the array elements using pointer! What will happen when

*(pi++); /* which is same as *(pi + 1) */
Firstly, expression in parenthesis is evaluated, 1 in the exp. (pi + 1) is scaled by the size of integer as

(pi + 1 * 4); equals (pi + 4);
which results in pointer to 2nd element ‘max[1]’ in array ‘max[]’. Now indirection is performed on the pointer

*(pi + 4); /* indirection performed */
which results in value of pointed to location i.e. value 2. This way, we can use pointer ‘pi’ to access elements in the array ‘max[]’.

Consider the fragment of code below to access the array ‘max[]’,

int max[5] = {1,2,3,4,5};
int *pi;
int i;

for (i = 0, pi = max; pi < &max[5]; pi++, i++)
printf("max[%d] has value %d\n", i, *pi);
Remember the Rules of Compatibility of Pointers while declaring and initializing pointer to access an array.

Top
05 Is Pointer more Efficient than Using Subscript to Access an Array in C Programming?
Question: Is Pointer more Efficient than using Subscript to Access an Array in C Programming?
Answer: Let’s first consider examples below,

int stud_passed[5] = {234, 11, 456, 99, 887};
int *pi;
int i;
Now, we try accessing the array ‘stud_passed[]’ using subscript and ptr-to-int, ‘pi’

for (i = 0; i < 5; i++)
stud_passed[i]; /* using subscript */

for (pi = stud_passed, i = 0; i < 5; i++, pi++)
*pi; /* using ptr-to-int */
Now, question is Which of the two is more efficient? Let’s unravel one by one, accessing the array ‘stud_passed[]’ using subscript indicates that ‘stud_passed[5]’ is a pointer constant so it can’t be modified, i.e. expression,

stud_passed++; /* 'stud_passed' is pointer constant */
doesn’t worth for any meaning and results in error. Further, during each iteration through for loop, index i changes. In first iteration,

stud_passed[0 * 4];
/* index i with value 0 is being scaled to type int */

during 2nd iteration,

stud_passed[1 * 4]; /* i is 1 */
during 3rd iteration,

stud_passed[2 * 4]; /* i is 2 */
and so on till for statement exits. This requires, in each iteration, i to be updated and scaled to integer followed by addition to the base address of the array and finally subscript operator performs to evaluate the value.

While using pointer ‘pi’ to access array ‘stud_passed[]’, multiplication and addition like arrays above are also performed and that in adjustment statement. But here’s a difference that through each iteration, statement

pi++; or
pi = pi + 1; /* 'pi' is pointer variable */
is incremented by same value (1 * 4). Further, this is computed once at compile time and so there are less no. of instructions executing at run time resulting in efficient code than using subscript.

Notice, however, that code fragment using pointer could be written more concisely as below,

for (pi = &stud_passed[0]; pi < &stud_passed[5]; )
*pi++;
But one shouldn’t compromise with Program Readability and Maintainability for smaller gains in efficiency.

Let’s take another example, where pointer and subscript are equally efficient,

float rain_fall[5];
float *fp;
int i;

for (i = 0; i < 5; i++)
rain_fall[i] = 0; /* clearing array 'rain_fall[]' */
using the ptr-to-float ‘fp’,

for (i = 0; i < 5; i++)
*(fp + i) = 0; /* clearing array 'rain_fall[]' */
In general, code with pointers can be more efficient than with subscripts but code with subscripts can’t be more efficient than with pointers.


Top
06 Are Expressions arrays[i] and i[arrays] same?
Question: Are Expressions arrays[i] and i[arrays] same?
Answer: We know that we can use pointer and indirection to access an array. Let’s try to rewrite the exp.

arrays[i];
using pointer as:
*(arrays + i);
which, of course, we can write as:

*(i + arrays); /* addition is 'commutative' */
which we rewrite in subscript form as:
i[arrays];
So, these two expressions are same! But writing this way is awkward and one should practice decent style of programming!

Top
07 Explain Array in C with Examples
This C Tutorial explains an Array in C with Example(s).
Answer: Let’s try to declare ’12’ integers below,

int jan = 1, feb = 2, march = 3, april = 4, may = 5, june = 6, july = 7,
august = 8, september = 9, october = 10, november = 11, december = 12;
/* 12 integers declared */
Well! I’ve declared an initialized ’12’ integers. But what about if we need some 196 integers, let’s say, for population in 196 different countries. Is this declaration really easy? And what will happen when it comes to access such variables? When passing them in a function as arguments? Aren’t you in trouble? Fortunately, here is a way to fix this issue, declare an array, initialize it and use it!

What’s an array? An array can be thought of as an arrangement of a specified number of elements of same kind stored in contiguous memory locations and this arrangement is given a name. For example,

count[10]; /* count an array of 10 something */
count is name of array immediately followed by a pair of subscripts ‘[]’ containing an expression which results in integer value specifying no. of elements in the array.

What’s type of 10 something? These something 10 can be integers, characters, floats etc. For example, if these are integers, then

int count[10]; /* count an array of 10 integers */
if these something are characters, then

char count[10]; /* count an array of 10 characters */
char *count[10]; /* count an array of 10 strings */
and so on.

Since, an array contains more elements of same type, it’s generally called as Vector as opposite to a single variable called Scalar. Elements in an array are stored in locations with offsets ranging from 0 through size of array minus 1. For example,

float marks[5] = {67, 89.5, 45.8, 60, 48.6};
/* marks contains 5 floats */
Let’s see how these 5 floats are organised in marks,

marks[0] = 67;
marks[1] = 89.5;
marks[2] = 45.8;
marks[3] = 60;
marks[4] = 48.6;
Notice that offsets begin with ZERO and last ‘valid one’ is 1 less than size of array. These offsets are also called as Indices.

Top
08 Are Pointers and Arrays Same in C?
Question: Are Pointers and Arrays Same in C
Answer: Let’s, first, see their declarations,

char name[20]; /* 'name[20]' a character array declared */
char alphabet;
char *cp = &alphabet; /* 'cp' pointer-to-character points to alphabet */
and now analyse them. When compiler comes across the statement

char name[20];
it allocates block of 20 bytes of memory in continuous locations, then creates array name ‘name’ and sets this to the beginning of the array. Therefore array is said to be vector. To confirm amount of memory allocated to ‘name[]’ we can use ‘sizeof operator’ as:

printf("Amount of memory allocated to array name[%d] is %d bytes.\n",
20, sizeof(name));
and when it reaches the statement

char *cp = &alphabet;
allocates a block of memory, 8 bytes on Linux System, names it ‘cp’ which is ptr-to-char and initializes it with address of character variable ‘alphabet’. Pointer, like other variable types, is said to be scalar.

printf("pointer-to-char 'cp' takes %d bytes of allocation.\n",
sizeof(cp));
Note that, on Linux System, pointer variable irrespective of its type, is allocated 8 bytes of memory.

Let’s turn to analyse contents of the two, viz. array ‘name[]’ and pointer-to-char ‘cp’,

name[20];
is an array of 20 characters. Array ‘name[20]’ can’t have address as its contents. Pointer-to-char ‘cp’, contains address of character variable ‘alphabet’.

Well! As we just observed that pointer contains address as value. for example,

printf("pointer-to-char 'cp' contains address %p of character variable "
"'alphabet'.\n", cp);
What will happen if we assign ‘cp’ address of some another character, for example,

char initial = 'X';
cp = &initial; /* 'cp' is assigned address of 'initial' */

‘cp’ now points to character variable ‘initial’ in the memory. This indicates that ‘cp’ can be assigned address of any character variable.

An array name also is an address or precisely a pointer constant, a constant address points to some fixed location in the memory. Like other constants, value of pointer constant can’t be modified i.e. statements like

name++;
isn’t valid. However, ‘cp’ can be used to point to where array ‘name’ points,

cp = name; /* type of array 'name' is pointer-to-char */
‘cp’ and ‘name’ both now point to array ‘name’.
Top
09 Can One-Dimensional Arrays be passed as Function Arguments in C Language?
This C Tutorial Explains One-Dimensional Arrays as Function Arguments in C Language with Example(s).
C is a modular programming language meaning that it allows us to organise large programs into self-contained modules called functions. Each function performs some dedicated task. For example,

void copy_str(char *dstr, char *sstr)
{
for (*dstr++ = *sstr++ != '\0')
;
}
Above function copies source string to destination string. We are familiar with using functions which we had passed scalar variables. For example,

int main(void)
{
int num1 = 10, num2 = 20;

swap(num1, num2); /* 'num1' and 'num2' are actual parameters */
printf("After calling \'swap()\', \'num1\' and \'num2\' are %d and "
"%d\n", num1, num2);
return 0;
}

void swap(int n, int m) /* 'n' and 'm' are formal parameters */
{
int temp;

/* logic for swapping two nos. */
temp = n;
n = m;
m = temp;

printf("In \'swap()\', \'n\' and \'m\' are %d and %d\n", n, m);
}
When function ‘swap()’ was called, actual values of ‘num1’ and ‘num2’ were passed to the function ‘swap()’ and initialized to the formal variables ‘n’ and ‘m’ in the function header. Function ‘swap()’, swapped them up and displayed the result. However, they aren’t swapped in ‘main()’ function. Because, ‘swap()’ performed on the copies of actual arguments.

In order values be swapped in ‘main()’ as well, should we call ‘swap()’ and pass the memory addresses of two variables so function ‘swap()’ performs on actual values instead of copies of them. Accordingly, formal arguments in function header must be declared of type pointer. So, function ‘swap()’ takes shape as:

advertisements

void swap(int *pi1, int *pi2) /* 'pi1' and 'pi2' are both pointer-to-int */
{
int temp;

temp = *pi1;
*pi1 = pi2;
*pi2 = temp;
}
Let’s now take an example of one-dimensional array,

float avg_life[10];
As array is a vector it can contain specified number of elements. In array ‘avg_life[10]’, there are 10 floats which are garbage values by default. Like scalars, if we call some function to pass arrays as values, entire array is to be copied to function parameter, wasting lots of time and memory, the critical resources of the system. Further this will slow down execution. In order to prevent wastage of critical resources, to speed up execution of the program, an array irrespective of its dimension is passed by address than by value. Called function receives the address of the array and accesses the array. Let’s see how address of an array is passed to the called function.

In order to receive the address of an array in called function, type of array must be known in advance and accordingly pointer of same type must be declared as formal parameter. For example, type of array ‘avg_life[10]’ is a pointer-to-float. Therefore, in the called function,

void clear(float *fp, int arr_size) /* 'fp' declared as pointer-to-float */
{
int i;

for (i = 0; i < arr_size; i++)
*fp++ = 0; /* clears the array */
}

What did you observe in above function? Only address of start of the array is passed to the function into ‘*fp’ rather than entire array is copied. Function ‘clear()’ using pointer-to-float ‘*fp’, no. of elements in the array and using pointer arithmetic accessed each array element and set it to 0. Thus, ‘clear()’ performed on the actual values of the array avg_life[]’.

There are situations where we need to prevent original data from accidental alterations by the called function, for example, copying a source string to destination string, we can define function prototype and function header as:

void copy_str(char *, const char *); /* prototype */

/* formal argument 'sstr' is ptr-to-const-char */
void copy_str(char *dstr, const char *sstr)
{
for (*dstr++ = *sstr++ != '\0')
;
}


Top
10 What do we mean by Static and Automatic Initialization of an Array in C?
This C Tutorial Explains Static and Automatic Initialization of an Array in C with Example(s).
Let’s recollect concept of automatic and static initialization from declaring and initializing a scalar variable,

auto int i; /* auto keyword optional */
can be written as:

int i; /* by default automatic */
What’s in ‘i’? When a variable’s declared automatic but not initialized, it contains garbage. Now we initialize integer ‘i’

i = 10; /* now 'i' contains value 10 */
What’s if a variable’s declared static?

/*
* static_ini1.c -- program shows use of static declaration and
* initialization
*/
#include

int main(void)
{
static int i; /* 'i' declared static */

printf("Default Value of "static variable i" is %dn", i);
return 0;
}
Output is as below:

Default Value of "static variable i" is 0
Here, static variable ‘i’, by default 0, didn’t seem to be of much use. Let’s modify the above program to use static variable in a function,

/*
* static_ini2.c -- program shows use of static declaration and
* initialization
*/
#include
void count(int);

int main(void)
{
int i; /* 'i' declared automatic */

for (i = 1; i <= 5; i++)
count(i);

return 0;
}

void count(int iteration)
{
static int i; /* 'i' initialized once */

printf("Value of "static int i" in count(%d) is %dn",
iteration, ++i);
}
Output follows:

Value of "static int i" in count(1) is 1
Value of "static int i" in count(2) is 2
Value of "static int i" in count(3) is 3
Value of "static int i" in count(4) is 4
Value of "static int i" in count(5) is 5
Notice that static variable ‘i’, with default value 0, retained its last modified value each time function ‘count()’ was called and exited. Thus, static variable is declared once and its life time is entire execution of the program. It’s neither created anew each time ‘count()’ was entered nor did it destroy when ‘count()’ exited. Therefore, a significant amount of time is saved in using static variable.

Let’s turn to consider declaration and initialization of one-dimensional array, for example,

int children[5] = {234, 11, 453, 1212, 6663};
which has assignments happening as below,

children[0] = 234;
children[1] = 11;
children[2] = 453;
children[3] = 1212;
children[4] = 6663;
Since an array usually have more elements, declaring an array to be automatic and initialized it within the function which needs to be called repeatedly wastes significant amount of time in each function call. Therefore, declaring an array to be static and initialized it within function which might be called several times is more efficient. For example,

/* static_arr.c -- program shows an array declared static */
#include
void update(int);

int main(void)
{
update(1);
update(0);
return 0;
}

void update(int FLAG)
{
static int count[10] = {12, 34, 45, 123, 1, 3, 56, 90, 88, 100};
int i;

if (FLAG) {
for(i = 0; i < 10; i++)
count[i] += 5;
printf("Updated data!n");
}
else {
printf("No need!n");
}
}
Output follows:

Updated data!
No need!
Analysing the output of the above program is an easy task! When ‘update(1)’ was called first time, if condition in the called function accounted for TRUE and thus array ‘count[]’ updated by incrementing each value in array by 5. Interesting point here is that array ‘count[]’ was declared and initialized statically just once in the called function ‘update()’ and therefore it retained its last modified values each time function ‘update()’ entered. When ‘update(0)’ was called else component of if construct executed and displayed massage “No need!”.

Top
11 What is Incomplete Initialization in C Programming?
This C Tutorial Explains Incomplete Initialization in C Programming with Example(s).
Let’s consider examples of incomplete initialization below,

int jams[5] = {1, 2, 3, 4, 5, 6};
int hats[5] = {1, 2, 3, 4};
Notice that ‘jams’ is an array of 5 integers while we are trying to pack it with 6 integers. What will happen then? Let’s explore,

/*
* arr_with_more_ele_than_size.c -- program shows can an array be
* initialized with more elements than its size
*/
#include
int main(void)
{
int i;
int jams[5] = {1, 2, 3, 4, 5, 6};

for (i = 0; i < 6; i++)
printf("jams[%d] is %d\n", i, jams[i]);
return 0;
}

Now, we observe the output below,

arr_with_more_elements_than_size.c:7:2: warning: excess elements in array
initializer [enabled by default]
arr_with_more_elements_than_size.c:7:2: warning: (near initialization
for ‘jams’) [enabled by default]
[root@localhost kar_arrays]# ./a.out
jams[0] is 1
jams[1] is 2
jams[2] is 3
jams[3] is 4
jams[4] is 5
jams[5] is 32767
Well! When we tried to pack into array ‘jams’ more elements than its size, it didn’t and issued instead a warning “more elements in the array initializer”.

Now, let’s turn to other side of coin; consider an array with less elements than its size, below,

/*
* arr_with_less_elem_than_size.c -- program shows can an array be
* initialized with less elements than its size
*/
#include
int main(void)
{
int i;
int hats[5] = {1,2,3,4};

for (i = 0; i < 5; i++)
printf("hats[%d] is %d\n", i, hats[i]);
return 0;
}

Observe the output below,

[root@localhost kar_arrays]# ./a.out
hats[0] is 1
hats[1] is 2
hats[2] is 3
hats[3] is 4
hats[4] is 0
Notice that if an array, for ex. hats[5], contains less no. of initializers, at least one, in the list than its size, initializers are assigned sequentially from index 0 through till last initializer is assigned. Rest of the elements are assigned to 0 automatically.


Top
12 Explain Character Array Initialization in C with Examples
This C Tutorial Explains Character Array Initialization in C with Example(s).
We already know about how to declare and initialize arrays. In particular, character arrays aren’t any exception! Let’s take an example of character array,

char name[] = {'c', 'h', 'r', 'i', 's', 't', 'o', 'p', 'h', 'e', 'r'};
Array ‘name’ contains 11 characters. While initializing ‘name’, list of 11 characters, each in single quotes and separated by comma with its adjacent character, put in a pair of curly braces. But this way of initialization is cumbersome at writing especially when long list of characters is to be typed in. Alternately, C standard gives shorthand notation to write initializer’s list. Below is an alternate way of writing the character array ‘name[]’,

char name[] = "christopher"; /* initializing 'name' */
But we, here, are a bit confused if name is a ‘String Literal’ or a character array containing 11 characters. Where’s the difference? Consider below given declaration and initialization,

char *name2 = "christopher"; /* is 'name2' a string literal? */
Both ‘name’ and ‘name2’ seems to be string literals. But difference between two is cleared by the context in which they are used. When ‘name’ has an initializer list, it’s called an array. Everywhere else, it’s a String literal. Therefore,

char name[] = "christopher";
is a character array. While

char *name2 = "christopher";
is a string literal. Actually, ‘name2’ is a pointer-to-char_string, points to string “christopher” wherever is stored in memory.

/*
* diff_char_arr_str.c -- program shows difference between character array
* and string Literal
*/
#include <stdio.h>
#include <string.h>

int main(void)
{
char name[] = "christopher"; /* character array */
char *name2 = "christopher"; /* string literal */

printf("name "%s" is an array and name2 "%s" is a string literal.n"
, name, name2);
return 0;
}
Output as:

name “christopher” is an array and name2 “christopher” is a string literal.


Top
13 What is a Multidimensional Array in C Programming?
This C Tutorial Explains Multidimensional Array in C Programming with Example(s).
An array with more than one dimension is called a multidimensional array. Consider an example below,

int hawks[5][3]; /* a two dimensional array */
int pieces[2][2][3]; /* a three dimensional array */
int overs[5][5][5][5]; /* a four dimensional array */
and so on. Let’s first explore how they are read,

int hawks[5][3];
‘hawks’ is an array of 5 something, each of which is an array of 3 integers, i.e. ‘hawks’ is an array of 5 arrays of 3 integers. Similarly, ‘pieces’ is an array of 2 arrays of two arrays of 3 integers.

O key! We now discuss how multi-dimensional arrays are initialized? let’s take, first, a 2-dim array below,

int hawks[5][3] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
/* 15 integers are in hawks */
Since ‘hawks’ contains 5 arrays of 3 integers each, i.e. ‘hawks’ contains 15 integers. These are allocated in continuous locations in memory. Since ‘hawks’ contains 5 arrays of 3 integers, we can rewrite the initialization as

int hawks[5][3] = {{1,2,3},{4,5,6},{7,8,9},{10,11,12},{13,14,15}};
/* initializer list contains 5 elements, each contains 3 integers */

Now, we consider a 3-dim array and try to initialize it,

int pieces[2][2][3] = {
{{1,2,3},{4,5,6}},
{{7,8,9},{10,11,12}}
};
‘pieces’ is an array of 2 arrays of 2 arrays of 3 integers. In fact, ‘pieces’ contains 12 integers. We can also remove the inner sets of curly braces and initialization comes to shape as:

int pieces[2][2][3] = {1,2,3,4,5,6,7,8,9,10,11,12};
However, this form of initialization isn’t easy in order to determine which element belongs to which dimension. Further, if we omit some trailing initializers from the list, we shall still have to type in long list. For ex.

int pieces[2][2][3] = {1,2,3,4,5,6,7,8,9};
/* three trailing initializers are omitted */
Also, in such initialization, we can omit initializers only from the end of list.

Once more, we consider pieces[2][2][3] and initialize it using inner sets of curly braces as below,

int pieces[2][2][3] = {
{{1,2,3},{4,5,6}},
{{7,8,9},{10,11,12}}
};


and observe that pieces has two arrays

1. {{1,2,3},{4,5,6}}
2. {{7,8,9},{10,11,12}}
Each array further contains two arrays of 3 integers each. With such initialization, don’t we find it easy to determine which element belongs to which dimension and also we can now omit trailing initializers from each list. Let’s try this out right now, below,

int pieces[2][2][3] = {
{{1},{4}},
{{7},{10}}
};
How easy it’s become to omit trailing initializers from each list and therefore, it’s become handy to type long list of initializers when only few initializers are given.

Remember that such initialization is very useful in writing multi-dimensional arrays having very few elements.


Top
14 Explain Pointer to Array in C with Examples
This C Tutorial Explains Pointer to Array in C with Example(s).
A pointer is a variable whose contents is an address of some location in memory. For example:

int val = 10, new = 20;
int *ptr = &val; /* 'ptr' points to 'val' */

ptr = &new; /* 'ptr' now points to 'new' */
Why do we need a pointer to an array? I recall, We have already seen that when we pass an array as a function argument, we use pointer as function parameter to receive the array, just start of array, and use this pointer to perform manipulations on the original values, if required, without copying the array into function. This saves critical resources time and memory. So, what about if we want a pointer to an array, let’s say one-dimensional array, for example:

int clubs[5] = {23, 55, 12};
As we know that name of an array is a pointer constant i.e. a constant address in memory and pointer contains an address. Therefore, we can declare a pointer to an array. But what type is it? For one-dimensional array ‘clubs[]’ which is an array of integers, type of array is pointer-to-int, so we write as:

int *ptr = clubs; /* 'clubs' is a constant address */
Now ‘ptr’ and ‘clubs’ have same contents i.e. same address. Therefore, ‘ptr’ points to array ‘clubs’. In fact, it points to first element ‘clubs[0]’ of array ‘clubs’. In order to have ‘ptr’ to point to next element, ‘clubs[1]’, in the array, we increment the ‘ptr’ by 1 as,

ptr++; /* 'ptr' is incremented by 1 */

and so on. Now, let’s consider a two-dimensional array and try declaring a ‘ptr’ to it.

int hawks[5][3]; /* a two dimensional array */
As we know that in order to declare a pointer to an array, we must know the type of array. What type of array ‘hawks’ is? As we see ‘hawks’ is an array of 5 arrays of 3 integers each. Deciphering type of array from its expression is a key point in declaring a pointer-to-array.

So, what type ‘hawks’ is? From the expression, it’s clear that ‘hawks’ is an array of arrays of 3 integers. So, ‘hawks’ contains elements as array of 3 ints. Therefore, type of ‘hawks’ is: array of array of 3 ints, so is type of pointer,

int (*ptr)[3] = hawks; /* 'ptr' points to 'hawks' */
Notice that we enclosed ‘ptr’ in a pair of parenthesis because subscript operator ‘[]’ have higher precedence than indirection operator (*). so, ‘ptr’ is a pointer-to-array-of_3ints, i.e. ‘ptr’ points to first element of ‘hawks’ which is an array of 3 integers. In fact, ‘ptr’ points to hawks[0], more precisely to hawks[0][0].

What happens if ‘ptr’ gets incremented by 1? That is,

ptr += 1; /* ? */
‘ptr’, since, points to an array of 3 integers, when gets incremented by 1,

ptr + 1;
1 is scaled by the size of element ‘ptr’ is pointing to, i.e. size of array of 3 integers. Therefore, ‘ptr’ points to next array of 3 integers which is ‘hawks[1][3]’ or more precisely ‘hawks[1][0]’ and so on.

Similarly, we can declare pointer to multi-dimensional arrays of higher dimensions. For example, pointer to 4-dimensional array,

int overs[5][5][5][5]; /* a four-dimensional array */
can be declared as

int (*ptr4)[5][5][5];
/* 'ptr' points to array of 5 arrays of 5 arrays of 5 ints */


Top
15 Can Multidimensional Arrays be Passed as Function Arguments in C?
This C Tutorial Explains Multidimensional Arrays Passed as Function Arguments in C with Example(s).
Let’s, first, take an example of a 2-dimensional array,

int hawks[4][5] = {{1,2,3,4,5},
{6,7,8,9,10},
{11,12,13,14,15},
{16,17,18,19,20},
}; /* hawks's initialized here */
In order to pass ‘hawks’ as a function argument, we must know type of array ‘hawks’, so that we would be able to declare correctly formal parameter for this in function prototype and in function header. What type of array ‘hawks’ is? ‘hawks’ is an array of 4 arrays of 5 integers each. Then, how to determine type of ‘hawks’? Because, ‘hawks’ is an array of 4 arrays of 5 integers, therefore each element of ‘hawks’ is an array of 5 integers. So, pointer declared to ‘hawks’ should be one which points to an array of 5 integers, i.e. an element of ‘hawks’. Let’s write pointer declaration as,

int (*ptr)[5]; /* 'ptr', a pointer-to-array-of-5-integers */

O key! Now, we try accessing array ‘hawks’ in function “access_multidimarr(int (*ptr)[5], int num)”. Note, here, that we have to pass number of arrays of integers i.e. no. of elements ‘hawks’ has to function since function “access_multidimarr()” can’t in any way determine what many elements to process. Let’s take a program with this function to access array ‘hawks’ in the function and observe the output,

/*
* multidimarr_fun_arg.c -- program shows if we can pass multidimensional
* array as function argument
*/
#include <stdio.h>
void access_multidimarr(int (*)[5], int); /* prototype */

int main(void)
{
int hawks[4][5] = {{1,2,3,4,5},
{6,7,8,9,10},
{11,12,13,14,15},
{16,17,18,19,20},
}; /* hawks's initialized */

printf("Now we access \'hawks[4][5]\'...\n");
access_multidimarr(hawks, 4); /* called the function */
return 0;
}

void access_multidimarr(int (*ptr)[5], int num)
{
int i, j;

printf("In function: accessing \'hawks\' using pointer to array.\n");
for (i = 0; i < num; i++) {
for (j = 0; j < 5; j++) {
printf("hawks[%d][%d] is %d\n", i, j, *(*ptr + j));
}
ptr++;
}
}
Here’s the output:

Now we access 'hawks[4][5]'...
In function: accessing 'hawks' using pointer to array.
hawks[0][0] is 1
hawks[0][1] is 2
hawks[0][2] is 3
hawks[0][3] is 4
hawks[0][4] is 5
hawks[1][0] is 6
hawks[1][1] is 7
hawks[1][2] is 8
hawks[1][3] is 9
hawks[1][4] is 10
hawks[2][0] is 11
hawks[2][1] is 12
hawks[2][2] is 13
hawks[2][3] is 14
hawks[2][4] is 15
hawks[3][0] is 16
hawks[3][1] is 17
hawks[3][2] is 18
hawks[3][3] is 19
hawks[3][4] is 20

So, we, here, learned how we passed a multi-dimensional array, ‘hawks’, as a function argument and accessed the same in the function.

Recall that we can pass any multi-dimensional array as a function argument if and only if we are able to find type of that array from its expression and consequently declare correctly pointer of that type in the function.


Top
16 Explain Array of Pointers in C with Examples
This C Tutorial Explains Array of Pointers in C with Examples.
Well! We have situations where we need several pointers, say several strings to be matched for desired one, for example, then declaring and initializing pointers one by one as scalar is a cumbersome job. We have a way out to this trouble and which is declare and initialize an array of pointers. Let’s go for it.

char *car_make[9] = {"Suzuki","Toyota","Nissan","Tata","BMW","Audi",
"Chevrolet","Honda","Mahindra"};
Let’s presume the declaration “char *car_make[9]” as an expression and evaluate it to understand about how to declare and initialize correctly an array of pointers.

In the expression

char *car_make[9]
subscript operator ‘[]’ being higher in precedence than indirection operator ‘*’ and therefore is evaluated first, results in 9 characters. Then, indirection is applied which results in 9 ‘pointers-to-char’ or 9 ‘pointers-to-strings’. Let’s rewrite the above expression

char *car_make[9]

as

char (*car_make)[9]
and this time, again, try to evaluate the expression.

This time, indirection operator ‘*’, enclosed in parenthesis, go first than subscript operator. This results in ‘pointer-to-something’. Then subscript operator evaluates to an ‘array of 9 characters’. And overall result is a ‘pointer-to-array_of_9_characters’, which is not what we are interested in. In fact, we require an array of pointers. Therefore, expression

char *car_make[9]
is what serves our purpose. Let’s see how this initialization takes place,

char *car_make[9] = {"Suzuki","Toyota","Nissan","Tata","BMW","Audi",
"Chevrolet","Honda","Mahindra"};

*car_make[0] = "Suzuki"; /* '*car_make[]' is a ptr-to-string */
*car_make[1] = "Toyota";
*car_make[2] = "Nissan";
*car_make[3] = "Tata";
*car_make[4] = "BMW";
*car_make[5] = "Audi";
*car_make[6] = "Chevrolet";
*car_make[7] = "Honda";
*car_make[8] = "Mahindra";
Let’s consider a program using the above array of ‘pointer-to-strigs’ to ensure if a given string is in the array or not.

/*
* arr_ptr2char.c -- program shows if a given string is matched in the list
* of strings
*/
#include <stdio.h>
#include <string.h>

/* function prototype */
void match_str(char const * const, char const * const[], int const);

int main(void)
{
char const *car_make[9] = {"Suzuki","Toyota","Nissan","Tata","BMW",
"Audi","Chevrolet","Honda","Mahindra"};
char to_search[15];

printf("Give choice of 'car make' u want to search for...n");
gets(to_search);
match_str(to_search, car_make, 9);
return 0;
}

void match_str(char const * const to_match, char const * const arr_str[],
int const size)
{
char const **check_make;

for (check_make = arr_str; check_make < arr_str + size; check_make++)
if (strcmp(to_match, *check_make) == 0) {
printf("Matched at location %d in car_make.n",
check_make - arr_str);
return;
}

printf("Not matched!n");
return;
}
Let’s now try out above program for some test-choices,

Give choice of 'car make' u want to search for...
Nissan
Matched at location 2 in car_make.

Give choice of 'car make' u want to search for...
Tata
Matched at location 3 in car_make.

Give choice of 'car make' u want to search for...
Ambassador
Not matched!


Top
17 Size of an Array using sizeof Operator OR strlen() Function in C Language
Question: Can we Determine Size of an Array using sizeof Operator and strlen() Function in C Language?
Answer: Let’s learn this by considering an example, and analysing it’s output when program is run on Linux System.

/*
* sizeof_vs_strlen.c -- program shows difference between using sizeof and
* strlen with array and string
*/
#include <stdio.h>
#include <string.h>

int main(void)
{
char msg[] = {'c','h','r','i','s','t','o','p','h','e','r'};
/* Character array */
char name1[] = "christopher"; /* character array */
char *name2 = "christopher"; /* string literal */

printf("sizeof: size of char array msg[] \"%s\" is %d bytes!\n",
msg, sizeof(msg));
printf("strlen: size of char array msg[] \"%s\" is %d bytes!\n",
msg, strlen(msg));

printf("sizeof: size of char array name1[] \"%s\" is %d bytes!\n",
name1, sizeof(name1));
printf("strlen: size of char array name1[] \"%s\" is %d bytes!\n",
name1, strlen(name1));

printf("sizeof: size of string \"%s\" is %d bytes!\n",
name2, sizeof(name2));
printf("strlen: size of string \"%s\" is %d bytes!\n",
name2, strlen(name2));

return 0;
}
Output follows:

sizeof: size of char array msg[] "christopher" is 11 bytes!
strlen: size of char array msg[] "christopher" is 11 bytes!
sizeof: size of char array name1[] "christopher" is 12 bytes!
strlen: size of char array name1[] "christopher" is 11 bytes!
sizeof: size of string "christopher" is 8 bytes!
strlen: size of string "christopher" is 11 bytes!
Notice that sizeof operator returns actual amount of memory allocated to the array including NULL byte if it’s included in initializer’s list or without it if it’s not there. Basically, sizeof operator is used to evaluate amount of memory, in bytes, allocated to its argument.

sizeof(arg); /* 'arg' can be any data or type */

In case of name2, which is a pointer to string “christopher”, sizeof returns size of pointer which is 8 bytes on Linux, although strlen() returned actual no. of characters in the string without counting NULL byte.

Remember that strlen() function primarily a string handling function used with strings and always returns actual no. of characters in the string without counting on NULL byte. We’ll see more about various string handling functions later.

Top
Render time: 0.30 seconds
7,457,392 unique visits