Array c


Array declaration

Array is a type consisting of a contiguously allocated nonempty sequence of objects with a particular element type. The number of those objects (the array size) never changes during the array lifetime.


In the declaration grammar of an array declaration, the type-specifier sequence designates the element type (which must be a complete object type), and the declarator has the form:

(optional)qualifiers(optional)expression(optional)attr-spec-seq(optional) (1)
qualifiers(optional)(optional)expression(optional)attr-spec-seq(optional) (2)
qualifiers(optional)attr-spec-seq(optional) (3)

1,2) General array declarator syntax

3) Declarator for VLA of unspecified size (can appear in function prototype scope only) where

expression - any expression other than comma operator, designates the number of elements in the array
qualifiers - any combination of , , or qualifiers, only allowed in function parameter lists; this qualifies the pointer type to which this array parameter is transformed
attr-spec-seq - (C23)optional list of attributes, applied to the declared array
float fa[11], *afp[17];// fa is an array of 11 floats// afp is an array of 17 pointers to floats


There are several variations of array types: arrays of known constant size, variable-length arrays, and arrays of unknown size.

[edit]Arrays of constant known size

If expression in an array declarator is an integer constant expression with a value greater than zero and the element type is a type with a known constant size (that is, elements are not VLA)(since C99), then the declarator declares an array of constant known size:

int n[10];// integer constants are constant expressionschar o[sizeof(double)];// sizeof is a constant expressionenum&#; MAX_SZ=&#;;int n[MAX_SZ];// enum constants are constant expressions

Arrays of constant known size can use array initializers to provide their initial values:

int a[5]=&#;1,2,3&#;;// declares int[5] initalized to 1,2,3,0,0char str[]="abc";// declares char[4] initialized to 'a','b','c','\0'

In function parameter lists, additional syntax elements are allowed within the array declarators: the keyword and qualifiers, which may appear in any order before the size expression (they may also appear even when the size expression is omitted).

In each function call to a function where an array parameter uses the keyword between and , the value of the actual parameter must be a valid pointer to the first element of an array with at least as many elements as specified by expression:

void fadd(double a[static10], constdouble b[static10])&#;for(int i =0; i <10; i++)&#;if(a[i]<)return; a[i]+= b[i];&#;&#;// a call to fadd may perform compile-time bounds checking// and also permits optimizations such as prefetching 10 doubles int main(void)&#;double a[10]=&#;0&#;, b[20]=&#;0&#;; fadd(a, b);// OKdouble x[5]=&#;0&#;; fadd(x, b);// undefined behavior: array argument is too small&#;

If qualifiers are present, they qualify the pointer type to which the array parameter type is transformed:

int f(constint a[20])&#;// in this function, a has type const int* (pointer to const int)&#;int g(constint a[const20])&#;// in this function, a has type const int* const (const pointer to const int)&#;

This is commonly used with the type qualifier:

void fadd(double a[staticrestrict10], constdouble b[staticrestrict10])&#;for(int i =0; i <10; i++)&#;// loop can be unrolled and reorderedif(a[i]<)break; a[i]+= b[i];&#;&#;

Variable-length arrays

If expression is not an integer constant expression, the declarator is for an array of variable size.

Each time the flow of control passes over the declaration, expression is evaluated (and it must always evaluate to a value greater than zero), and the array is allocated (correspondingly, lifetime of a VLA ends when the declaration goes out of scope). The size of each VLA instance does not change during its lifetime, but on another pass over the same code, it may be allocated with a different size.

&#;int n =1; label:int a[n];// re-allocated 10 times, each with a different sizeprintf("The array has&#;%zu elements\n", sizeof a /sizeof*a);if(n++<10)goto label;// leaving the scope of a VLA ends its lifetime&#;

If the size is , the declaration is for a VLA of unspecified size. Such declaration may only appear in a function prototype scope, and declares an array of a complete type. In fact, all VLA declarators in function prototype scope are treated as if expression were replaced by .

void foo(size_t x, int a[*]);void foo(size_t x, int a[x])&#;printf("%zu\n", sizeof a);// same as sizeof(int*)&#;

Variable-length arrays and the types derived from them (pointers to them, etc) are commonly known as "variably-modified types" (VM). Objects of any variably-modified type may only be declared at block scope or function prototype scope.

externint n;int A[n];// Error: file scope VLAexternint(*p2)[n];// Error: file scope VMint B[];// OK: file-scope array of constant known sizevoid fvla(int m, int C[m][m]);// OK: prototype-scope VLA

VLA must have automatic or allocated storage duration. Pointers to VLA, but not VLA themselves may also have static storage duration. No VM type may have linkage.

void fvla(int m, int C[m][m])// OK: block scope/auto duration pointer to VLA&#;typedefint VLA[m][m];// OK: block scope VLAint D[m];// OK: block scope/auto duration VLA// static int E[m]; // Error: static duration VLA// extern int F[m]; // Error: VLA with linkageint(*s)[m];// OK: block scope/auto duration VM s =malloc(m *sizeof(int));// OK: s points to VLA in allocated storage// extern int (*r)[m]; // Error: VM with linkagestaticint(*q)[m]=&B;// OK: block scope/static duration VM}&#;

Variably-modified types cannot be members of structs or unions.

struct tag &#;int z[n];// Error: VLA struct memberint(*y)[n];// Error: VM struct member&#;;
(since C99)

If the compiler defines the macro constant __STDC_NO_VLA__ to integer constant 1, then VLA and VM types are not supported.

(since C11)

[edit]Arrays of unknown size

If expression in an array declarator is omitted, it declares an array of unknown size. Except in function parameter lists (where such arrays are transformed to pointers) and when an initializer is available, such type is an incomplete type (note that VLA of unspecified size, declared with as the size, is a complete type)(since C99):

externint x[];// the type of x is "array of unknown bound of int"int a[]=&#;1,2,3&#;;// the type of a is "array of 3 int"

Within a struct definition, an array of unknown size may appear as the last member (as long as there is at least one other named member), in which case it is a special case known as flexible array member. See struct for details:

struct s &#;int n;double d[];&#;;// s.d is a flexible array member struct s *s1 =malloc(sizeof(struct s)+(sizeof(double)*8));// as if d was double d[8]
(since C99)


If an array type is declared with a , , or (since C99) qualifier (which is possible through the use of typedef), the array type is not qualified, but its element type is:

(until C23)

An array type and its element type are always considered to be identically qualified, except that an array type is never considered to be -qualified.

(since C23)
typedefint A[2][3];const A a =&#;&#;4, 5, 6&#;, &#;7, 8, 9&#;&#;;// array of array of const intint* pi = a[0];// Error: a[0] has type const int*void*unqual_ptr = a;// OK until C23; error since C23// Notes: clang applies the rule in C++/C23 even in CC17 modes

is not allowed to be applied to an array type, although an array of atomic type is allowed.

typedefint A[2];// _Atomic A a0 = {0}; // Error// _Atomic(A) a1 = {0}; // Error _Atomic int a2[2]=&#;0&#;;// OK _Atomic(int) a3[2]=&#;0&#;;// OK
(since C11)


Objects of array type are not modifiable lvalues, and although their address may be taken, they cannot appear on the left hand side of an assignment operator. However, structs with array members are modifiable lvalues and can be assigned:

int a[3]=&#;1,2,3&#;, b[3]=&#;4,5,6&#;;int(*p)[3]=&a;// okay, address of a can be taken// a = b; // error, a is an arraystruct&#;int c[3];&#; s1, s2 =&#;3,4,5&#;; s1 = s2;// okay: can assign structs holding array members

[edit]Array to pointer conversion

Any lvalue expression of array type, when used in any context other than

undergoes an implicit conversion to the pointer to its first element. The result is not an lvalue.

If the array was declared , the behavior of the program that attempts such conversion is undefined.

int a[3]=&#;1,2,3&#;;int* p = a;printf("%zu\n", sizeof a);// prints size of arrayprintf("%zu\n", sizeof p);// prints size of a pointer

When an array type is used in a function parameter list, it is transformed to the corresponding pointer type: int f(int a[2]) and int f(int* a) declare the same function. Since the function's actual parameter type is pointer type, a function call with an array argument performs array-to-pointer conversion; the size of the argument array is not available to the called function and must be passed explicitly:

void f(int a[], int sz)// actually declares void f(int* a, int sz)&#;for(int i =0; i < sz;++i)printf("%d\n", a[i]);&#;int main(void)&#;int a[10]; f(a, 10);// converts a to int*, passes the pointer&#;

[edit]Multidimensional arrays

When the element type of an array is another array, it is said that the array is multidimensional:

// array of 2 arrays of 3 ints eachint a[2][3]=&#;&#;1,2,3&#;, // can be viewed as a 2x3 matrix&#;4,5,6&#;&#;;// with row-major layout

Note that when array-to-pointer conversion is applied, a multidimensional array is converted to a pointer to its first element, e.g., pointer to the first row:

int a[2][3];// 2x3 matrixint(*p1)[3]= a;// pointer to the first 3-element rowint b[3][3][3];// 3x3x3 cubeint(*p2)[3][3]= b;// pointer to the first 3x3 plane

Multidimensional arrays may be variably modified in every dimension if VLAs are supported(since C11):

int n =10;int a[n][2*n];
(since C99)


Zero-length array declarations are not allowed, even though some compilers offer them as extensions (typically as a pre-C99 implementation of flexible array members).

If the size expression of a VLA has side effects, they are guaranteed to be produced except when it is a part of a sizeof expression whose result doesn't depend on it:

int n =5;size_t sz =sizeof(int(*)[n++]);// may or may not increment n


  • C17 standard (ISO/IEC ):
  • Array declarators (p: )
  • C11 standard (ISO/IEC ):
  • Array declarators (p: )
  • C99 standard (ISO/IEC ):
  • Array declarators (p: )
  • C89/C90 standard (ISO/IEC ):
  • Array declarators

[edit]See also


C - Arrays

Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, , and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and , numbers[99] to represent individual variables. A specific element in an array is accessed by an index.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

Arrays in C

Declaring Arrays

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows −

type arrayName [ arraySize ];

This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type. For example, to declare a element array called balance of type double, use this statement −

double balance[10];

Here balance is a variable array which is sufficient to hold up to 10 double numbers.

Initializing Arrays

You can initialize an array in C either one by one or using a single statement as follows −

double balance[5] = {, , , , };

The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ].

If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write −

double balance[] = {, , , , };

You will create exactly the same array as you did in the previous example. Following is an example to assign a single element of the array −

balance[4] = ;

The above statement assigns the 5th element in the array with a value of All arrays have 0 as the index of their first element which is also called the base index and the last index of an array will be total size of the array minus 1. Shown below is the pictorial representation of the array we discussed above −

Array Presentation

Accessing Array Elements

An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example −

double salary = balance[9];

The above statement will take the 10th element from the array and assign the value to salary variable. The following example Shows how to use all the three above mentioned concepts viz. declaration, assignment, and accessing arrays −

Live Demo

#include <stdio.h> int main () { int n[ 10 ]; /* n is an array of 10 integers */ int i,j; /* initialize elements of array n to 0 */ for ( i = 0; i < 10; i++ ) { n[ i ] = i + ; /* set element at location i to i + */ } /* output each array element's value */ for (j = 0; j < 10; j++ ) { printf("Element[%d] = %d\n", j, n[j] ); } return 0; }

When the above code is compiled and executed, it produces the following result −

Element[0] = Element[1] = Element[2] = Element[3] = Element[4] = Element[5] = Element[6] = Element[7] = Element[8] = Element[9] =

Arrays in Detail

Arrays are important to C and should need a lot more attention. The following important concepts related to array should be clear to a C programmer −

Sr.No.Concept & Description
1Multi-dimensional arrays

C supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array.

2Passing arrays to functions

You can pass to the function a pointer to an array by specifying the array's name without an index.

3Return array from a function

C allows a function to return an array.

4Pointer to an array

You can generate a pointer to the first element of an array by simply specifying the array name, without any index.

  1. Farmasi usa
  2. Acer monitor sound bar
  3. Fox news alexandria ocasio cortez

C Arrays

C arrays

An array is a variable that can store multiple values. For example, if you want to store integers, you can create an array for it.

How to declare an array?

dataType arrayName[arraySize];

For example,

float mark[5];

Here, we declared an array, , of floating-point type. And its size is 5. Meaning, it can hold 5 floating-point values.

It's important to note that the size and type of an array cannot be changed once it is declared.

Access Array Elements

You can access elements of an array by indices.

Suppose you declared an array as above. The first element is , the second element is and so on.

C Array declaration

Few keynotes:

  • Arrays have 0 as the first index, not 1. In this example, is the first element.
  • If the size of an array is , to access the last element, the index is used. In this example,
  • Suppose the starting address of is d. Then, the address of the will be d. Similarly, the address of will be d and so on.
    This is because the size of a is 4 bytes.

How to initialize an array?

It is possible to initialize an array during declaration. For example,

You can also initialize an array like this.

Here, we haven't specified the size. However, the compiler knows its size is 5 as we are initializing it with 5 elements.

Initialize an array in C programming


mark[0] is equal to 19 mark[1] is equal to 10 mark[2] is equal to 8 mark[3] is equal to 17 mark[4] is equal to 9

Change Value of Array elements

Input and Output Array Elements

Here's how you can take input from the user and store it in an array element.

Here's how you can print an individual element of an array.

Example 1: Array Input/Output


Here, we have used a  loop to take 5 inputs from the user and store them in an array. Then, using another  loop, these elements are displayed on the screen.

Example 2: Calculate Average


Here, we have computed the average of numbers entered by the user.

Access elements out of its bound!

Suppose you declared an array of 10 elements. Let's say,

int testArray[10];

You can access the array elements from to .

Now let's say if you try to access . The element is not available. This may cause unexpected output (undefined behavior). Sometimes you might get an error and some other time your program may run correctly.

Hence, you should never access elements of an array outside of its bound.

Multidimensional arrays

In this tutorial, you learned about arrays. These arrays are called one-dimensional arrays.

In the next tutorial, you will learn about multidimensional arrays (array of an array).

C Programming Tutorial - 41 - Sorting Arrays

Arrays in C/C++


An array in C/C++ or be it in any programming language is a collection of similar data items stored at contiguous memory locations and elements can be accessed randomly using indices of an array.  They can be used to store collection of primitive data types such as int, float, double, char, etc of any particular type. To add to it, an array in C/C++ can store derived data types such as the structures, pointers etc. Given below is the picture representation of an array.


Take a step-up from those "Hello World" programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.

Why do we need arrays? 
We can use normal variables (v1, v2, v3, ..) when we have a small number of objects, but if we want to store a large number of instances, it becomes difficult to manage them with normal variables. The idea of an array is to represent many instances in one variable.
Array declaration in C/C++: 


Note: In above image int a[3]={[0&#;1]=3}; this kind of declaration has been obsolete since GCC

There are various ways in which we can declare an array. It can be done by specifying its type and size, by initializing it or both.

Array declaration by specifying size 



Array declaration by initializing elements



Array declaration by specifying size and initializing elements



Advantages of an Array in C/C++: 

  1. Random access of elements using array index.
  2. Use of less line of code as it creates a single array of multiple elements.
  3. Easy access to all the elements.
  4. Traversal through the array becomes easy using a single loop.
  5. Sorting becomes easy as it can be accomplished by writing less line of code.

Disadvantages of an Array in C/C++: 

  1. Allows a fixed number of elements to be entered which is decided at the time of declaration. Unlike a linked list, an array in C is not dynamic.
  2. Insertion and deletion of elements can be costly since the elements are needed to be managed in accordance with the new memory allocation.

Facts about Array in C/C++: 

  • Accessing Array Elements: 
    Array elements are accessed by using an integer index. Array index starts with 0 and goes till size of array minus 1.
  • Name of the array is also a pointer to the first element of array.













5 2 5

No Index Out of bound Checking: 
There is no index out of bounds checking in C/C++, for example, the following program compiles fine but may produce unexpected output when run.  














In C, it is not a compiler error to initialize an array with more elements than the specified size. For example, the below program compiles fine and shows just Warning.








prog.c: In function 'main': prog.c warning: excess elements in array initializer int arr[2] = { 10, 20, 30, 40, 50 }; ^ prog.c note: (near initialization for 'arr') prog.c warning: excess elements in array initializer int arr[2] = { 10, 20, 30, 40, 50 }; ^ prog.c note: (near initialization for 'arr') prog.c warning: excess elements in array initializer int arr[2] = { 10, 20, 30, 40, 50 }; ^ prog.c note: (near initialization for 'arr')
  • Note: The program won&#;t compile in C++. If we save the above program as a .cpp, the program generates compiler error &#;error: too many initializers for &#;int [2]'&#;


The elements are stored at contiguous memory locations 














OutputSize of integer in this compiler is 4 Address arr[0] is 0x7ffe75c Address arr[1] is 0x7ffe75c Address arr[2] is 0x7ffe75c Address arr[3] is 0x7ffe75cc Address arr[4] is 0x7ffe75c


Another way to traverse the array









Output11 12 13 14 15 16 By Other Method: 11 12 13 14 15 16


Array vs Pointers 
Arrays and pointer are two different things (we can check by applying sizeof). The confusion happens because array name indicates the address of first element and arrays are always passed as pointers (even if we use square bracket). Please see Difference between pointer and array in C? for more details.
What is vector in C++? 
A vector in C++ is a class in STL that represents an array. The advantages of vector over normal arrays are, 


  • We do not need pass size as an extra parameter when we declare a vector i.e, Vectors support dynamic sizes (we do not have to initially specify size of a vector). We can also resize a vector.
  • Vectors have many in-built function like, removing an element, etc.


To know more about functionalities provided by vector, please refer vector in C++ for more details.





Related Articles
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 





C array


  • An array is a collection of data items, all of the same type, accessed using a common name.
  • A one-dimensional array is like a list;  A two dimensional array is like a table;  The C language places no limits on the number of dimensions in an array, though specific implementations may.
  • Some texts refer to one-dimensional arrays as vectors, two-dimensional arrays as matrices, and use the general term arrays when the number of dimensions is unspecified or unimportant.

Declaring Arrays

  • Array variables are declared identically to variables of their data type, except that the variable name is followed by one pair of square [ ] brackets for each dimension of the array.
  • Uninitialized arrays must have the dimensions of their rows, columns, etc. listed within the square brackets.
  • Dimensions used when declaring arrays in C must be positive integral constants or constant expressions.
    • In C99, dimensions must still be positive integers, but variables can be used, so long as the variable has a positive value at the time the array is declared. ( Space is allocated only once, at the time the array is declared. The array does NOT change sizes later if the variable used to declare it changes. )

  • Examples:
  • int i, j, intArray[ 10 ], number; float floatArray[ ]; int tableArray[ 3 ][ 5 ]; /* 3 rows by 5 columns */ const int NROWS = ; // ( Old code would use #define NROWS ) const int NCOLS = ; // ( Old code would use #define NCOLS ) float matrix[ NROWS ][ NCOLS ];
  • C99 Only Example:
  • int numElements; printf( "How big an array do you want? " ); scanf( "%d", &numElements; ) if( numElements <= 0 ) { printf( "Error - Quitting\n" ); exit( 0 ); } double data[ numElements ]; // This only works in C99, not in plain C

Initializing Arrays

  • Arrays may be initialized when they are declared, just as any other variables.
  • Place the initialization data in curly {} braces following the equals sign.  Note the use of commas in the examples below.
  • An array may be partially initialized, by providing fewer data items than the size of the array.  The remaining array elements will be automatically initialized to zero.
  • If an array is to be completely initialized, the dimension of the array is not required.  The compiler will automatically size the array to fit the initialized data.  ( Variation:  Multidimensional arrays - see below. )
  • Examples:
  • int i = 5, intArray[ 6 ] = { 1, 2, 3, 4, 5, 6 }, k; float sum = f, floatArray[ ] = { f, f, f }; double piFractions[ ] = { , , };

Designated Initializers:

  • In C99 there is an alternate mechanism, that allows you to initialize specific elements, not necessarily at the beginning.
  • This method can be mixed in with traditional iniitalization
  • For example:
int numbers[ ] = { 1, 2, 3, [10] = 10, 11, 12, [60] = 50, [42] = };
    • In this example,the first three elements are initialized to 1, 2, and 3 respectively.
    • Then element 10 ( the 11th element ) is initialized to 10
    • The next two elements ( 12th and 13th ) are initialized to 11 and 12 respectively.
    • Element number 60 ( the 61st ) is initialized to 50, and number 42 ( the 43rd ) to
      • ( Note that the designated initializers do not need to appear in order. )
    • As with traditional methods, all uninitialized values are set to zero.
    • If the size of the array is not given, then the largest initialized position determines the size of the array.

Using Arrays

  • Elements of an array are accessed by specifying the index ( offset ) of the desired element within square [ ] brackets after the array name.
  • Array subscripts must be of integer type.  ( int, long int, char, etc. )
  • VERY IMPORTANT: Array indices start at zero in C, and go to one less than the size of the array.  For example, a five element array will have indices zero through four.  This is because the index in C is actually an offset from the beginning of the array.  ( The first element is at the beginning of the array, and hence has zero offset. )
  • Landmine:  The most common mistake when working with arrays in C is forgetting that indices start at zero and stop one less than the array size.
  • Arrays are commonly used in conjunction with loops, in order to perform the same calculations on all ( or some part ) of  the data items in the array.

Sample Programs Using 1-D Arrays

  • The first sample program uses loops and arrays to calculate the first twenty Fibonacci numbers.  Fibonacci numbers are used to determine the sample points used in certain optimization methods.
  • /* Program to calculate the first 20 Fibonacci numbers. */ #include <stdlib.h>
  • Exercise: What is the output of the following program:
  • /* Sample Program Using Arrays */ #include <stdlib.h>

Multidimensional Arrays

  • Multi-dimensional arrays are declared by providing more than one set of square [ ] brackets after the variable name in the declaration statement.
  • One dimensional arrays do not require the dimension to be given if the array is to be completely initialized.  By analogy, multi-dimensional arrays do not require the first dimension to be given if the array is to be completely initialized.  All dimensions after the first must be given in any case.
  • For two dimensional arrays, the first dimension is commonly considered to be the number of rows, and the second dimension the number of  columns.  We will use this convention when discussing two dimensional arrays.
  • Two dimensional arrays are considered by C/C++ to be an array of ( single dimensional arrays ).  For example, "int numbers[ 5 ][ 6 ]"  would refer to a single dimensional array of 5 elements, wherein each element is a single dimensional array of 6 integers.  By extension, "int numbers[ 12 ][ 5 ][ 6 ]" would refer to an array of twelve elements, each of which is a two dimensional array, and so on.
  • Another way of looking at this is that C stores two dimensional arrays by rows, with all elements of a row being stored together as a single unit.  Knowing this can sometimes lead to more efficient programs. 
  • Multidimensional arrays may be completely initialized by listing all data elements within a single pair of curly {} braces, as with single dimensional arrays.
  • It is better programming practice to enclose each row within a separate subset of curly {} braces, to make the program more readable.  This is required if any row other than the last is to be partially initialized.  When subsets of braces are used, the last item within braces is not followed by a comma, but the subsets are themselves separated by commas.
  • Multidimensional arrays may be partially initialized by not providing complete initialization data.  Individual rows of a multidimensional array may be partially initialized, provided that subset braces are used.
  • Individual data items in a multidimensional array are accessed by fully qualifying an array element.  Alternatively, a smaller dimensional array may be accessed by partially qualifying the array name.  For example, if  "data" has been declared as a three dimensional array of floats, then data[ 1 ][ 2 ][ 5 ] would refer to a float, data[ 1 ][ 2 ] would refer to a one-dimensional array of floats, and data[ 1 ] would refer to a two-dimensional array of floats.  The reasons for this and the incentive to do this relate to memory-management issues that are beyond the scope of these notes.

Sample Program Using 2-D Arrays

/* Sample program Using 2-D Arrays */ #include <stdlib.h>


Material Below This Line Not Covered in CS Until Later

Passing Arrays to Functions ( in C++ )

  • Recall that we know two methods for passing ordinary data to functions:
    • Pass-by-Value, in which the function receives a copy and all changes are local, and
    • Pass-by-Reference, in which the names of the variables in the called and calling functions become aliases, and changes made in the called function DO affect the variables in the calling function.
  • If an individual element of an array is passed to a function, it is passed according to its underlying data type.
    • So if nums was declared as a one-dimensional array of ints, then passing nums[ i ] to a function would behave the exact way as passing any other int - Either pass-by-value or pass-by-reference, depending on how the function is written.
  • When an entire array is passed to a function, however, it is always passed by reference.
    • ( It is actually passed by pointer/address, which is not covered here, but functionally it is pass-by-reference. )
    • The net result, is that when an entire array is passed to a function, and the function changes variables stored in that array, it does affect the data in the calling function's array.
    • Because arrays are passed by reference, there is generally no need for a function to "return" an array. - It merely needs to fill in an array provided by the calling function. ( It is possible for functions to return arrays but it requires the use of pointers and addresses, and frequently dynamic memory allocation, all of which is beyond the scope of this course. )
    • In order to prevent the function from changing the array values, the array parameter can be modified with the keyword const.
  • When an entire array is passed to a function, the size of the array is usually passed as an additional argument.
  • For a one dimensional array, the function's formal parameter list does not need to specify the dimension of the array.  If such a dimension is provided, the compiler will ignore it.
  • For a multi-dimensional array, all dimensions except the first must be provided in a functions formal parameter list.  The first dimension is optional, and will be ignored by the compiler.
  • A partially qualified multi-dimensional array may be passed to a function, and will be treated as an array of lower dimension.  For example, a single row of a two dimensional array may be passed to a function which is expecting a one dimensional array.  ( Question:  Why is it possible to pass a row this way, but not a column? )
  • Examples:  Note the use of arrays and functions in the following sample program.  Note that in the calculation of max4, we have passed a two dimensional array containing two rows of three elements as if it were a single dimensional array of six elements.  This is cheating, but it happens to work because of the way that the rows of a multidimensional array are stored.
  • /* Program Illustrating the use of Arrays and Functions */ #include <iostream> using namespace std; // Finds max in the array float maxArray( const float numbers[ ], int arraySize, int & errorCode ); int main( void ) { float array1[ ] = { , , , }; float array2[ 2 ][ 3 ] = { { , , }, { , , ; } errorCode = 0; max = numbers[ 0 ]; for( i = 1; i < arraySize; i++ ) max = ( numbers[ i ] > max ) ? numbers[ i ] : max; return max; }


Write the following functions:

  • double average( const double x[ ], int nValues, int & errorCode );
    • Calculates the average of the values in x.
    • nValues is how many elements to calculate
    • errorCode should be set to 0 if no errors or -1 if errors are encountered.
  • double dot( const double x[ ], const double y[ ], int nValues, int & errorCode );
    • Calculates the dot product of x and y.
    • nValues is how many elements to calculate
    • errorCode should be set to 0 if no errors or -1 if errors are encountered.
  • int calcSins( const double x[ ], double sinX[ ], int nValues );
    • Calculates the sin of each element of x, and stores the results in sinX.
    • nValues is how many elements to calculate
    • The return value is the actual number of values calculated. It should be equal to nValues if all goes well, or some other value ( e.g. zero ) if there is a problem.

Character Strings as Arrays of Characters

  • The "string" class type is a new addition to C++, which did not exist in traditional C.
  • The traditional method for handling character strings is to use an array of characters.
  • A null byte ( character constant zero, '\0' ) is used as a terminator signal to mark the end of the string.
  • Ordinary quoted strings ( "Please enter a number > " ) are stored as null-terminated arrays of characters.
  • The cstring library contains a number of functions for dealing with traditional arrays of characters.
  • C++ string objects can be initialized using C-style traditional arrays of characters:
    • string prompt = "Please enter your choice > ";
C Programming Tutorial 83 - Printing Array with Loop

Arrays in C

Arrays are useful critters that often show up when it would be convenient to have one name for a group of variables of the same type that can be accessed by a numerical index. For example, a tic-tac-toe board can be held in an array and each element of the tic-tac-toe board can easily be accessed by its position (the upper left might be position 0 and the lower right position 8). At heart, arrays are essentially a way to store many values under the same name. You can make an array out of any data-type including structures and classes.

One way to visualize an array is like this: [][][][][][] Each of the bracket pairs is a slot in the array, and you can store information in slot--the information stored in the array is called an element of the array. It is very much as though you have a group of variables lined up side by side.

Let's look at the syntax for declaring an array. int examplearray[]; /* This declares an array */ This would make an integer array with slots (the places in which values of an array are stored). To access a specific part element of the array, you merely put the array name and, in brackets, an index number. This corresponds to a specific element of the array. The one trick is that the first index number, and thus the first element, is zero, and the last is the number of elements minus one. The indices for a element array range from 0 to Be careful not to "walk off the end" of the array by trying to access element !

What can you do with this simple knowledge? Let's say you want to store a string, because C has no built-in datatype for strings, you can make an array of characters.

For example: char astring[]; will allow you to declare a char array of elements, or slots. Then you can receive input into it from the user, and when the user types in a string, it will go in the array, the first character of the string will be at position 0, the second character at position 1, and so forth. It is relatively easy to work with strings in this way because it allows support for any size string you can imagine all stored in a single variable with each element in the string stored in an adjacent location--think about how hard it would be to store nearly arbitrary sized strings using simple variables that only store one value. Since we can write loops that increment integers, it's very easy to scan through a string: #include <stdio.h> int main() { char astring[10]; int i = 0; /* Using scanf isn't really the best way to do this; we'll talk about that in the next tutorial, on strings */ scanf( "%s", astring ); for ( i = 0; i < 10; ++i ) { if ( astring[i] == 'a' ) { printf( "You entered an a!\n" ); } } getchar(); } Let's look at something new here: the scanf function call is a tad different from what we've seen before. First of all, the format string is '%s' instead of '%d'; this just tells scanf to read in a string instead of an integer. Second, we don't use the ampersand! It turns out that when we pass arrays into functions, the compiler automatically converts the array into a pointer to the first element of the array. In short, the array without any brackets will act like a pointer. So we just pass the array directly into scanf without using the ampersand and it works perfectly.

Also, notice that to access the element of the array, we just use the brackets and put in the index whose value interests us; in this case, we go from 0 to 9, checking each element to see if it's equal to the character a. Note that some of these values may actually be uninitialized since the user might not input a string that fills the whole array--we'll look into how strings are handled in more detail in the next tutorial; for now, the key is simply to understand the power of accessing the array using a numerical index. Imagine how you would write that if you didn't have access to arrays! Oh boy.

Multidimensional arrays are arrays that have more than one index: instead of being just a single line of slots, multidimensional arrays can be thought of as having values that spread across two or more dimensions. Here's an easy way to visualize a two-dimensional array: [][][][][] [][][][][] [][][][][] [][][][][] [][][][][] The syntax used to actually declare a two dimensional array is almost the same as that used for declaring a one-dimensional array, except that you include a set of brackets for each dimension, and include the size of the dimension. For example, here is an array that is large enough to hold a standard checkers board, with 8 rows and 8 columns: int two_dimensional_array[8][8]; You can easily use this to store information about some kind of game or to write something like tic-tac-toe. To access it, all you need are two variables, one that goes in the first slot and one that goes in the second slot. You can make three dimensional, four dimensional, or even higher dimensional arrays, though past three dimensions, it becomes quite hard to visualize.

Setting the value of an array element is as easy as accessing the element and performing an assignment. For instance, <arrayname>[<arrayindexnumber>] = <value> for instance, /* set the first element of my_first to be the letter c */ my_string[0] = 'c'; or, for two dimensional arrays <arrayname>[<arrayindexnumber1>][<arrayindexnumber2>] = <whatever>; Let me note again that you should never attempt to write data past the last element of the array, such as when you have a 10 element array, and you try to write to the [10] element. The memory for the array that was allocated for it will only be ten locations in memory, (the elements 0 through 9) but the next location could be anything. Writing to random memory could cause unpredictable effects--for example you might end up writing to the video buffer and change the video display, or you might write to memory being used by an open document and altering its contents. Usually, the operating system will not allow this kind of reckless behavior and will crash the program if it tries to write to unallocated memory.

You will find lots of useful things to do with arrays, from storing information about certain things under one name, to making games like tic-tac-toe. We've already seen one example of using loops to access arrays; here is another, more interesting, example! #include <stdio.h> int main() { int x; int y; int array[8][8]; /* Declares an array like a chessboard */ for ( x = 0; x < 8; x++ ) { for ( y = 0; y < 8; y++ ) array[x][y] = x * y; /* Set each element to a value */ } printf( "Array Indices:\n" ); for ( x = 0; x < 8;x++ ) { for ( y = 0; y < 8; y++ ) { printf( "[%d][%d]=%d", x, y, array[x][y] ); } printf( "\n" ); } getchar(); }

Just to touch upon a final point made briefly above: arrays don't require a reference operator (the ampersand) when you want to have a pointer to them. For example: char *ptr; char str[40]; ptr = str; /* Gives the memory address without a reference operator(&) */ As opposed to int *ptr; int num; ptr = &num; /* Requires & to give the memory address to the ptr */ The fact that arrays can act just like pointers can cause a great deal of confusion. For more information please see our Frequently Asked Questions.

Quiz yourself
Previous: Structures
Next: Strings
Back to C Tutorial Index


You will also be interested:

C Array

next →← prev

An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C programming language which can store the primitive type of data such as int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as pointers, structure, etc. The array is the simplest data structure where each data element can be randomly accessed by using its index number.

C array is beneficial if you have to store similar elements. For example, if we want to store the marks of a student in 6 subjects, then we don't need to define different variables for the marks in the different subject. Instead of that, we can define an array which can store the marks in each subject at the contiguous memory locations.

By using the array, we can access the elements easily. Only a few lines of code are required to access the elements of the array.

Properties of Array

The array contains the following properties.

  • Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
  • Elements of the array are stored at contiguous memory locations where the first element is stored at the smallest memory location.
  • Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given base address and the size of the data element.

Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.

3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.

Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.

Declaration of C Array

We can declare an array in the c language in the following way.

Now, let us see the example to declare the array.

Here, int is the data_type, marks are the array_name, and 5 is the array_size.

Initialization of C Array

The simplest way to initialize an array is by using the index of each element. We can initialize each element of the array by using the index. Consider the following example.

initialization of array in c language

C array example


C Array: Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

In such case, there is no requirement to define the size. So it may also be written as the following code.

Let's see the C program to declare and initialize the array in C.


C Array Example: Sorting an array

In the following program, we are using bubble sort method to sort the array in ascending order.

Program to print the largest and second largest element of the array.

Next TopicTwo Dimensional Array in C

← prevnext →


2301 2302 2303 2304 2305