Arrays are used to store a number of items in one single variable. They are usually placed in the same segment of memory with accessible elements for each . Think of a bead as a and a bead necklace as an array. This article will explain to you the tricks to C++ .
Let's say you want to fill up an array () with a number of values (beads).
#include
using namespace std;
int main(){
int [50];
return 0;
}
This allocates 50 elements of memory in the stack (since it is an integer: it is 50 bytes) called the array .
#include
using namespace ;
int main(){
int [3] = { 5, 1, 4}
// the above is the same as below for necklace2:
int necklace2[3];
necklace2[0] = 5;
necklace2[1] = 1;
necklace2[2] = 4;
cout << " and Necklace2 are equivalent!";
0;
}
Using the second way to declare the array, you can skip indexes (in the following example we skipped index 3 and index 5).
#include
using namespace ;
int main(){
int [50];
[0] = 43;
[1] = 321;
[4] = 500;
[6] = 4;
0;
}
Remember that an array[3] can have 4 different values, since the index starts from zero.
Multidimensional Arrays
can be multidimensional much like matrices.
#include
using namespace ;
int main(){
int [50][40][30];
[5][0][0] = 50;
[5][0][1] = 550;
0;
}
You can loop through them easily, you can place variables in each [] bracket and then change the variables.
Arrays as Function Parameters
can be as parameters inside functions. However, you must give the size of the array to the function because it cannot tell how large the array is through "sizeof".
#include
using namespace ;
void displayArray(int array[], int sizeOfArray){
for(int i = 0; i < sizeOfArray; i++){
cout << "Index: " << i << " :: Value: " << array[i] << endl;
}
}
int main(){
int [50];
[0] = 10;
[1] = 4;
[2] = 50;
int sizearray = 3;
// DO NOT try to access that are not declared.
displayArray( , sizearray);
0;
}
Don't try to loop through an array in places where it isn't defined, because you'll get a crash (segmentation fault).
Determining Size of an Array
You can determine the size of an array in this way:
#include
using namespace ;
int main(){
int [4];
[0] = 5;
[1] = 6;
[2] = 9;
[3] = 10;
cout << "Size Of Array: " << sizeof( )/sizeof( [0]);
0;
}
[0]'s size is an integer's size, which is simply 4 bytes. If it was char, it would be 1 byte. This should give you the correct value of the size (4 in this case because 16/4 = 4).