converting String.data() into an array
I want to take a string,and populate an array with its values. I know the length of the string is 16. I have tried
char *bit_number[16];
bit_number = bin.data();
and
char bit_number[16];
bit_number = bin.data();
I don't understand what String.data() is returning, why can't I assign it directly to an array? I'm getting compiler errors:
error: incompatible types in assignment of ‘const char*’ to ‘char* [16]’
and
error: incompatible types in assignment of ‘const char*’ to ‘开发者_C百科char [16]’
You need to copy the contents:
Assuming bin
is a std::string
:
char bit_numer[16];
copy( bin.begin(), bin.end(), bit_number );
This is all kinds of risky, however. What if your bin
has 17 characters ?
By the way, your original code:
char *bit_number[16];
...doesn't allocate an array of 16 char
s as you may expect. It allocated an array of 16 char*
. Most probably not what you're wanting.
You can use std::string::c_str()
to get access to the char array, and then use strcpy
to move it over to the new array.
string s = "1234";
char arr[5] = { 0 };
strcpy(arr, s.c_str());
If you want the dest array null-terminated, that's an extra line of code, and maybe an extra byte in your target array to accommodate it.
In your first example you have an array of 16 pointers to char. That's not what you want.
In your second example you have the types correct but you cannot assign the pointer (returned from data()) directly to the array because their types are not compatible - you have to copy the referenced data from one location to the other.
What do you need that char
array for, anyway? And are you sure whatever is in you string will fit into it? (There's a whole class of bugs coming from the use of arrays, and a famous one, too: buffer overruns.) You're very likely much better off using std::vector
, which resizes dynamically:
std::vector<char> v( bin.begin(), bin.end() );
If you need the array to pass it to a C API function that doesn't know how to handle a std::vector
, you can access the underlying array of the vector by doing the somewhat cryptic &v[0]
or &*v.begin()
. (Beware that you must check whether the vector is not empty before accessing its first element that way.)
精彩评论