c++ - How to create an array when the size is a variable not a constant?

C++ - How to create an array when the size is a variable not a constant?

In C++, if you need to create an array where the size is determined at runtime (i.e., not known at compile-time), you should use dynamic memory allocation. This can be done using raw pointers and new, or more conveniently, with modern C++ constructs like std::vector from the Standard Library.

1. Using Raw Pointers and new

You can use new to allocate memory for an array whose size is determined at runtime. Here's how:

Example Code

#include <iostream> int main() { int size; std::cout << "Enter the size of the array: "; std::cin >> size; // Allocate memory for the array int* array = new int[size]; // Initialize and use the array for (int i = 0; i < size; ++i) { array[i] = i * 2; // Example initialization } // Print the array for (int i = 0; i < size; ++i) { std::cout << "array[" << i << "] = " << array[i] << std::endl; } // Deallocate memory delete[] array; return 0; } 

Explanation

  1. Dynamic Allocation: new int[size] allocates memory for an array of int with the given size. The size is provided at runtime.

  2. Access and Use: You can access the array elements using the subscript operator ([]), just like with static arrays.

  3. Deallocate Memory: Use delete[] to free the memory when it is no longer needed to avoid memory leaks.

2. Using std::vector

A more modern and convenient way to handle dynamic arrays is by using std::vector, which is a part of the C++ Standard Library. std::vector automatically manages memory and can be resized dynamically.

Example Code

#include <iostream> #include <vector> int main() { int size; std::cout << "Enter the size of the array: "; std::cin >> size; // Create a vector with the given size std::vector<int> vec(size); // Initialize and use the vector for (int i = 0; i < size; ++i) { vec[i] = i * 2; // Example initialization } // Print the vector for (int i = 0; i < size; ++i) { std::cout << "vec[" << i << "] = " << vec[i] << std::endl; } // No need to manually deallocate memory; std::vector handles it automatically return 0; } 

Explanation

  1. Create a Vector: std::vector<int> vec(size); creates a vector of int with size elements. The vector automatically manages memory.

  2. Access and Use: You can use vec[i] to access and modify elements, similar to a raw array.

  3. Automatic Management: std::vector takes care of memory management and resizing. You do not need to explicitly deallocate memory.

Summary

  • Raw Pointers: Use new and delete[] for manual memory management. Suitable for low-level control but requires careful handling.
  • std::vector: Use std::vector for dynamic arrays. It provides automatic memory management and additional features, making it the preferred choice in modern C++.

In most cases, std::vector is recommended due to its ease of use and safety features.

Examples

  1. "C++ - Creating a dynamic array using new operator with variable size"

    Description: Use the new operator to create a dynamic array with a size specified by a variable.

    #include <iostream> int main() { int size; std::cout << "Enter the size of the array: "; std::cin >> size; int* array = new int[size]; // Fill the array with values for (int i = 0; i < size; ++i) { array[i] = i; } // Print the array for (int i = 0; i < size; ++i) { std::cout << array[i] << " "; } std::cout << std::endl; // Don't forget to free the memory delete[] array; return 0; } 
  2. "C++ - Using std::vector to create an array with variable size"

    Description: Use std::vector from the Standard Template Library (STL) to create an array with a variable size.

    #include <iostream> #include <vector> int main() { int size; std::cout << "Enter the size of the array: "; std::cin >> size; std::vector<int> array(size); // Fill the array with values for (int i = 0; i < size; ++i) { array[i] = i; } // Print the array for (int i = 0; i < size; ++i) { std::cout << array[i] << " "; } std::cout << std::endl; return 0; } 
  3. "C++ - Creating a variable-sized array on the stack using Variable Length Arrays (VLAs) (C++11 and later)"

    Description: Use Variable Length Arrays (VLAs), a feature available in C++11 and later for stack allocation of arrays with variable sizes. Note that VLAs are not standard C++ and may not be supported by all compilers.

    #include <iostream> int main() { int size; std::cout << "Enter the size of the array: "; std::cin >> size; int array[size]; // VLA (Variable Length Array), not standard in C++ // Fill the array with values for (int i = 0; i < size; ++i) { array[i] = i; } // Print the array for (int i = 0; i < size; ++i) { std::cout << array[i] << " "; } std::cout << std::endl; return 0; } 
  4. "C++ - Using std::unique_ptr for a dynamic array with variable size"

    Description: Use std::unique_ptr to manage a dynamic array with variable size, ensuring automatic memory management.

    #include <iostream> #include <memory> int main() { int size; std::cout << "Enter the size of the array: "; std::cin >> size; std::unique_ptr<int[]> array(new int[size]); // Fill the array with values for (int i = 0; i < size; ++i) { array[i] = i; } // Print the array for (int i = 0; i < size; ++i) { std::cout << array[i] << " "; } std::cout << std::endl; return 0; } 
  5. "C++ - Creating a dynamic 2D array with variable sizes using new operator"

    Description: Use the new operator to create a dynamic 2D array where both dimensions are specified by variables.

    #include <iostream> int main() { int rows, cols; std::cout << "Enter the number of rows and columns: "; std::cin >> rows >> cols; int** array = new int*[rows]; for (int i = 0; i < rows; ++i) { array[i] = new int[cols]; } // Fill the array with values for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { array[i][j] = i * cols + j; } } // Print the array for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { std::cout << array[i][j] << " "; } std::cout << std::endl; } // Free the memory for (int i = 0; i < rows; ++i) { delete[] array[i]; } delete[] array; return 0; } 
  6. "C++ - Using std::vector<std::vector<int>> for a dynamic 2D array with variable sizes"

    Description: Use std::vector to create a dynamic 2D array with variable sizes, leveraging the power of STL containers.

    #include <iostream> #include <vector> int main() { int rows, cols; std::cout << "Enter the number of rows and columns: "; std::cin >> rows >> cols; std::vector<std::vector<int>> array(rows, std::vector<int>(cols)); // Fill the array with values for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { array[i][j] = i * cols + j; } } // Print the array for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { std::cout << array[i][j] << " "; } std::cout << std::endl; } return 0; } 
  7. "C++ - Allocating a dynamic array using malloc and free with variable size"

    Description: Use malloc to allocate a dynamic array with a size specified by a variable and free to deallocate it.

    #include <iostream> #include <cstdlib> int main() { int size; std::cout << "Enter the size of the array: "; std::cin >> size; int* array = (int*)malloc(size * sizeof(int)); // Fill the array with values for (int i = 0; i < size; ++i) { array[i] = i; } // Print the array for (int i = 0; i < size; ++i) { std::cout << array[i] << " "; } std::cout << std::endl; // Free the memory free(array); return 0; } 
  8. "C++ - Resizing an array using std::vector::resize with variable size"

    Description: Use std::vector::resize to adjust the size of a vector dynamically based on a variable.

    #include <iostream> #include <vector> int main() { int size; std::cout << "Enter the size of the array: "; std::cin >> size; std::vector<int> array; array.resize(size); // Fill the array with values for (int i = 0; i < size; ++i) { array[i] = i; } // Print the array for (int i = 0; i < size; ++i) { std::cout << array[i] << " "; } std::cout << std::endl; return 0; } 
  9. "C++ - Using std::array for fixed-size arrays and switching to std::vector for dynamic sizing"

    Description: Use std::array for fixed-size arrays when the size is known at compile time, and switch to std::vector for variable sizes.

    #include <iostream> #include <array> #include <vector> int main() { int fixedSize = 5; std::array<int, 5> fixedArray = {1, 2, 3, 4, 5}; std::cout << "Fixed array: "; for (int i = 0; i < fixedSize; ++i) { std::cout << fixedArray[i] << " "; } std::cout << std::endl; int size; std::cout << "Enter the size of the dynamic array: "; std::cin >> size; std::vector<int> dynamicArray(size); // Fill the dynamic array with values for (int i = 0; i < size; ++i) { dynamicArray[i] = i; } // Print the dynamic array std::cout << "Dynamic array: "; for (int i = 0; i < size; ++i) { std::cout << dynamicArray[i] << " "; } std::cout << std::endl; return 0; } 
  10. "C++ - Using std::shared_ptr to manage dynamic arrays with variable size"

    Description: Use std::shared_ptr to manage dynamic arrays with variable sizes, ensuring proper memory management.

    #include <iostream> #include <memory> int main() { int size; std::cout << "Enter the size of the array: "; std::cin >> size; std::shared_ptr<int[]> array(new int[size]); // Fill the array with values for (int i = 0; i < size; ++i) { array[i] = i; } // Print the array for (int i = 0; i < size; ++i) { std::cout << array[i] << " "; } std::cout << std::endl; return 0; } 

More Tags

computational-geometry sidekiq uifont dot-matrix android-selector divide-and-conquer gspread mat-pagination appstore-approval tr

More Programming Questions

More Mortgage and Real Estate Calculators

More Weather Calculators

More Electrochemistry Calculators

More Trees & Forestry Calculators