Variables

Array in C

Arrays are used to assign a series of elements of the same type in consecutive memory locations; to define a list of elements. They work similar to variables, except they contain multiple values at different indices.


Syntax
dataType arrayName [arraySize];  //Declaring array 

 //Initializing an array all in one line, can omit the arraySize with this method  
dataType arrayName[arraySize] = { arrayElement1, arrayElement2, … , arrayElementN};

arrayName[elementPosition] = arrayElement; //To set a value at a specific position in the array 

variableType Variable = arrayName[elementPosition]; //To access a specific element and store in a variable

Notes

Arrays are initialized with a size. The array index range is 0 to the initialized size minus 1. This means that the first index in the array is 0, and the last is size minus 1. Trying to access an index outside the index range will result in an error.

dataType can be any C data type, and all elements in the array must be of this data type. arrayName is defined by the programmer. arraySize and elementPosition are integers.

A matrix (array defined by rows and columns) can also be created in the same way by adding a second set of square brackets where required (dataType[rows][columns]).


Example
int array[] = {1, 2, 3}; //initialize an array, one line 

int secondArray[2];  //declare array, assign later
secondArray[0] = 0;
secondArray[1] = 1; //will make an array with values (0, 1)

int startValue = array[0]; //will return a value of 1

See Also
Documentation

GNU C Manual - Arrays

Add to Slack

< Constants   |   Pointers >

© 2019 SyntaxDB. All Rights Reserved.