How to initialize and assign values to a C++ array?

In C++, there are multiple ways to initialize and assign values to an array. Here are some commonly used methods:

  1. Initialize the list using parentheses.
int arr[] = {1, 2, 3, 4, 5};
  1. Assign values one by one using a loop.
int arr[5];
for (int i = 0; i < 5; i++) {
    arr[i] = i + 1;
}
  1. Copy the values of another array to the target array using the memcpy function.
int source[] = {1, 2, 3, 4, 5};
int destination[5];
memcpy(destination, source, sizeof(source));
  1. Use the fill function to set all elements of the array to a specific value.
int arr[5];
std::fill(arr, arr + 5, 0);

Please note that there are other more convenient methods for initializing arrays introduced after the C++11 standard, such as using brace initializers and the std::array container.

bannerAds