I know I can do this in C++:
string s[] = {"hi", "there"};
But is there anyway to delcare an array this way without delcaring string s[]
?
e.g.
void foo(string[] strArray){ // some code } string s[] = {"hi", "there"}; // Works foo(s); // Works foo(new string[]{"hi", "there"}); // Doesn't work
A more convenient way to initialize a C string is to initialize it through character array: char char_array[] = "Look Here"; This is same as initializing it as follows: char char_array[] = { 'L', 'o', 'o', 'k', ' ', 'H', 'e', 'r', 'e', '\0' };
Highlights: There are four methods of initializing a string in C: Assigning a string literal with size. Assigning a string literal without size. Assigning character by character with size.
You can also initialize the String Array as follows:String[] strArray = new String[3]; strArray[0] = “one”; strArray[1] = “two”; strArray[2] = “three”; Here the String Array is declared first. Then in the next line, the individual elements are assigned values.
Initialize Arrays in C/C++ c. The array will be initialized to 0 if we provide the empty initializer list or just specify 0 in the initializer list.
In C++11 you can. A note beforehand: Don't new
the array, there's no need for that.
First, string[] strArray
is a syntax error, that should either be string* strArray
or string strArray[]
. And I assume that it's just for the sake of the example that you don't pass any size parameter.
#include <string> void foo(std::string* strArray, unsigned size){ // do stuff... } template<class T> using alias = T; int main(){ foo(alias<std::string[]>{"hi", "there"}, 2); }
Note that it would be better if you didn't need to pass the array size as an extra parameter, and thankfully there is a way: Templates!
template<unsigned N> void foo(int const (&arr)[N]){ // ... }
Note that this will only match stack arrays, like int x[5] = ...
. Or temporary ones, created by the use of alias
above.
int main(){ foo(alias<int[]>{1, 2, 3}); }
Prior to C++11, you cannot initialise an array using type[]. However the latest c++11 provides(unifies) the initialisation, so you can do it in this way:
string* pStr = new string[3] { "hi", "there"};
See http://www2.research.att.com/~bs/C++0xFAQ.html#uniform-init
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With