- Declaring Arrays: In C++, we can declare an array by specifying its data type, followed by the identifier (name), and the number of elements in square brackets. Here is an example:
1 int myArray[5];
- Initializing Arrays: After declaring an array, we can initialize its elements by assigning values to each element individually or by using an initializer list. Here are examples of both approaches:
1 // Approach 1: Initializing each element individually
2 int myArray[5];
3 myArray[0] = 10;
4 myArray[1] = 20;
5 myArray[2] = 30;
6 myArray[3] = 40;
7 myArray[4] = 50;
8
9 // Approach 2: Using an initializer list
10 int myArray[5] = {10, 20, 30, 40, 50};
- Manipulating Arrays: Once an array is declared and initialized, we can manipulate its elements using their indices. Here are examples of reading and modifying elements in an array:
1 // Reading the first element in the array
2 int firstElement = myArray[0];
3
4 // Modifying the third element in the array
5myArray[2] = 99;
- Passing Arrays to Functions: In C++, arrays cannot be passed directly to functions. Instead, we can pass a pointer to the first element of the array. Here is an example of a function that takes a pointer to an integer and the size of the array:
1 void printArray(int* array, int size) {
2 for (int i = 0; i < size; i++) {
3 cout << array[i] << " ";
4 }
5 cout << endl;
6}
This function can be called by passing a pointer to the first element of an array and the size of the array:
1 int myArray[5] = {10, 20, 30, 40, 50};
2 printArray(myArray, 5);
Note that if the array size is not specified, the function cannot determine the size of the array. Therefore, it is common to pass the array size as a second argument when dealing with arrays in C++.
About Author
Discover more from SURFCLOUD TECHNOLOGY
Subscribe to get the latest posts sent to your email.