What is an array in C/C++? If you don't know, please join Quantrimang.com to learn what you need to know about C++/C!
An array is a type of data structure in the C/C++ programming language that stores a sequential set of elements of the same type with a fixed length. Arrays are commonly used to store sets of data, but they are also useful for storing a set of variables of the same type.
Instead of declaring variables discretely, like variables bien1, variable1,… and variable99, you can declare an array of values like variable[0]bien[1] and … bien[99] to represent discrete values. A specific element of the array can be accessed via index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address corresponds to the last element of the array.
Why do we need to use arrays?
You can use normal array variables (v1, v2, v3…) when there are a small number of objects. However, if you want to store many cases, managing them will be more difficult than with normal variables. The idea for the creation of arrays represents many cases of using variables.
Advantage:
- Code optimization: You can extract or classify data effectively.
- Random access: Get data located at an index location.
Disadvantages:
Size limitation: Can only store fixed size of elements in array. It does not scale at runtime..
Array vs Pointer
Array and pointer are two different elements in C/C++ programming. The confusion often arises because the array name refers to the address of the first element, and arrays are often passed in pointer (even when you use square brackets). Therefore, please be careful before using arrays and pointers in C/C++ programming.
Declaring arrays in C/C++
To declare an array in C/C++, you specify the type of the element and the number of elements required by that variable as follows:
Kieu Ten_mang [ Kich_co_mang ];
This is a one-dimensional array. Kich_co_mang must be an integer greater than 0 and Kieu must be valid in C/C++ language. For example, declare a balance array with 10 elements of type double, using the following statement:
char balance[10];
Initializing arrays in C/C++
You can initialize arrays in C/C++ either element by element or using a statement like below:
int balance[5] = {15, 20, 25, 30, 35};
The number of values in curly brackets {} cannot be greater than the number of elements declared in square brackets [].
If you do not declare the array size, the array will be large enough to hold the initialized values. So if you write like below you will still get the same array as above:
int balance[] = {15, 20, 25, 30, 35};
You can create the same array as you did in the previous example.
balance[4] = 35;
The statement above assigns the 5th element of the array the value 35. All arrays have a first index of 0, this is called the base index, and the last element of the array has an index of 0. equal to the size of the array minus 1. Below is a graphical representation of the string declared above through the index:
Accessing array elements in C/C++
An array is accessed by indexing the array name. Here's a way to access an array value:
int hocphi = hocphik60[55];
The above statement takes the 56th element of the array and assigns this value to the variable hocphi. Here is an example of usage with all the descriptions above:
#include
using namespace std;
#include
using std::setw;
int main ()
{
int n[10];
//n la mot mang gom 10 so nguyen
//khoi tao gia tri cac phan tu cua mang n la 0
for (int i = 0; i
This program uses functions setw(so_nguyen) in C/C++ to format output. Here, the so_nguyen parameter is a number indicating the width of the result you want to display. For example, with so_nguyen is 3, which means you reserve 3 positions to print the results. If the result to be displayed is redundant, it will be truncated. If it is missing, more space will be inserted. The setw() function is used for both cout and cin.
Running the above C/C++ program will produce the following results:
Details about arrays in C/C++
Arrays are a very important part of the C/C++ language. Below are important definitions related to a particular array that are presented more clearly for C/C++ programmers:
Concept | Describe |
---|---|
Multidimensional array in C/C++ |
C/C++ supports multidimensional arrays. The simplest form of this array is a two-dimensional array |
Pointer to an array in C/C++ |
You can point to the first element of an array simply by specifying the array name, not an index. |
Pass array to function as parameter in C/C++ |
You can pass a pointer to an array to the function by specifying the array name rather than an index |
Return array from function in C/C++ |
C/C++ allows a function to return an array |
Multidimensional array in C++
C++ supports multidimensional arrays. Below is the general form of a multidimensional array declaration:
kieu_du_lieu ten_mang[kich_co_1][kich_co_2]...[kich_co_N];
For example, the following declaration creates a 3-dimensional array of integers: 5. 10. 4:
int hocphi[5][10][4];
Two-dimensional array in C++
The simplest form of a multidimensional array is a two-dimensional array. A two-dimensional array is essentially a list of one-dimensional arrays. To declare a two-dimensional integer array with sizes x, y, you should write as follows:
kieu_du_lieu ten_mang [ x ][ y ];
Here, type_name can be any valid data type and name_name will be a valid C++ identifier.
A two-dimensional array can be like a table that has x rows and y columns. A two-dimensional array a containing 3 rows and 4 columns can be displayed as follows:
Thus, each element in array a is identified by an element name in type a[i][j]where a is the array name and i, j are subscripts – indices that uniquely identify each element in a.
Initialize two-dimensional array in C++
Multidimensional arrays can be initialized by specifying square bracket values for each row. The following is a row with 3 rows and each row contains 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* khoi tao gia tri cho hang ma co chi muc la 0 */
{4, 5, 6, 7} , /* khoi tao gia tri cho hang ma co chi muc la 1 */
{8, 9, 10, 11} /* khoi tao gia tri cho hang ma co chi muc la 2 */
};
The braces, which indicate row values, are optional. The following initialization is equivalent to the above example:
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
Accessing elements of a two-dimensional array in C++
Two-dimensional array elements are accessed using indices, for example row index and column index. For example:
int val = a[2][3];
The above command will access the 4th element from the 3rd row of the array. You can check it again in the diagram above. Let us now look at the example below, where we have used nested loops to process a two-dimensional array:
include
using namespace std;
int main ()
{
//mang sau co 5 hang va 2 cot.
int a[5][2] = {{0,0}, {1,2}, {2,4}, {3,6},{4,8}};
//hien thi gia tri cua cac phan tu trong mang
for (int i = 0; i
Running the above C++ program will produce the following results:
As the above section explained, you can have arrays of any number of dimensions, but most arrays you create will be one or two dimensional.
Pointer to an array in C++
You may not understand this chapter until you have read the chapter on Pointers in C++.
So assuming you have some understanding of pointers in C++, let's get started: An array name is a constant pointer to the first element of the array. Therefore, in the declaration:
double phithuebao[50];
phithuebao is a pointer to &phithuebao[0]which is the address of the first element of the phithuebao array. Therefore, the following program fragment assigns p the address of the first element of phithuebao:
double *p;
double phithuebao[10];
p = phithuebao;
Using array names as constant pointers is legal, and vice versa. Therefore, *(phithuebao + 4) is the official way to access data at phithuebao[4].
Once you store the address of the first element in p, you can access the array elements using *p, *(p+1), *(p+2), … Below is an example Example to show all the concepts mentioned above:
#include
using namespace std;
int main ()
{
//mang sau co 5 phan tu.
double phithuebao[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;
p = phithuebao;
// hien thi gia tri cac phan tu trong mang
cout
Running the above C++ program will produce the following results:
In the above example, p is a pointer to double, which means it can hold the address of a variable of type double. Once we have the address in p, then *p will provide the value available at the address stored in p, as we showed in the example above.
Passing arrays as function parameters in C++
Return array from function in C++
C++ does not allow you to return an entire array as a parameter to a function. However, you can return a pointer to an array by specifying the array name without an index. You will learn about pointers in the next chapter, so you can skip this chapter until you understand the concept of Pointers in C++.
If you want to return a one-dimensional array from a function, you will have to declare a function that returns a pointer as in the following example:
int * tenHam()
{
.
.
.
}
The second point to remember is that C++ does not support returning the address of a local variable outside the function, so you will have to define the local variable as a Static variable.
Now, suppose the following function will generate 10 random numbers and return them using an array and call this function as follows:
#include
#include
#include /* thu vien cho ham srand, rand */ using namespace std;
// phan dinh nghia cua ham de tao va tra ve cac so ngau nhien.
int * soNgauNhien( )
{
static int r[10];
srand( (unsigned)time( NULL ));
for (int i = 0; i
Running the above C++ program will produce the following results: