How to use Pointers In C++
Pointers are the symbolic representation of an address. In simple words, a pointer is something that stores the address of a variable in it. In this method, an array of string literals is created by an array of pointers in which each pointer points to a particular string.
Example:
C++
// C++ program to demonstrate // array of strings using // pointers character array #include <iostream> // Driver code int main() { // Initialize array of pointer const char * colour[4] = { "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:
- The number of strings is fixed, but needn’t be. The 4 may be omitted, and the compiler will compute the correct size.
- These strings are constants and their contents cannot be changed. Because string literals (literally, the quoted strings) exist in a read-only area of memory, we must specify “const” here to prevent unwanted accesses that may crash the program.
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