Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ string array initialization

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 
like image 227
poy Avatar asked Mar 08 '12 23:03

poy


People also ask

How do I initialize a string array in C?

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' };

Can you initialize a string in C?

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.

How do you declare an array of strings?

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.

Does C initialize arrays to 0?

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.


2 Answers

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}); } 
like image 116
Xeo Avatar answered Sep 24 '22 06:09

Xeo


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

like image 29
Guangchun Avatar answered Sep 23 '22 06:09

Guangchun