Dec 30, 2012 at 1:54am
i am not really sure what to do.
char a[];
I thought that this was the way to declare an unknown array?
I was initially trying to convert the string into an array of chars.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
#include <iostream>
#include <string>
#include <typeinfo>
using namespace std;
char str_char(string s){
int len = s.length();
char array[len];
for (int i=0; i < len; i++){
array[i] = s[i];
}
return array[len];
}
int main(){
string s = "test";
char a[];
a = str_char(s);
cout << a;
}
|
which gives the error of:
test.cpp:21:9: error: storage size of ‘a’ isn’t known
Last edited on Dec 30, 2012 at 1:54am
Dec 30, 2012 at 2:09am
A string is already an array of chars. You can obtain a pointer to the first element of that array with &s[0]
, s.data()
, or s.c_str()
.
If you want to copy them out to a vector, it's just
vector<char> a(s.begin(), s.end());
Last edited on Dec 30, 2012 at 2:10am