How to use a 2D array In C++
A 2-D array is the simplest form of a multidimensional array in which it stores the data in a tabular form. This method is useful when the length of all strings is known and a particular memory footprint is desired. Space for strings will be allocated in a single block
Example:
C++
// C++ program to demonstrate // array of strings using // 2D character array #include <iostream> // Driver code int main() { // Initialize 2D array char colour[4][10] = { "Blue" , "Red" , "Orange" , "Yellow" }; // Printing Strings stored in 2D array for ( int i = 0; i < 4; i++) std::cout << colour[i] << "\n" ; return 0; } |
Output
Blue Red Orange Yellow
Explanation:
- Both the number of strings and the size of the strings are fixed. The 4, again, may be left out, and the appropriate size will be computed by the compiler. The second dimension, however, must be given (in this case, 10), so that the compiler can choose an appropriate memory layout.
- Each string can be modified but will take up the full space given by the second dimension. Each will be laid out next to each other in memory, and can’t change size.
- Sometimes, control over the memory footprint is desirable, and this will allocate a region of memory with a fixed, regular layout.
Array of Strings in C++ – 5 Different Ways to Create
In C++, a string is usually just an array of (or a reference/points to) characters that ends with the NULL character ‘\0‘. A string is a 1-dimensional array of characters and an array of strings is a 2-dimensional array of characters where each row contains some string.
Below are the 5 different ways to create an Array of Strings in C++:
- Using Pointers
- Using 2-D Array
- Using the String Class
- Using the Vector Class
- Using the Array Class
Contact Us