I have char a[] = "abc".
I need to do: char b [] = a i.e essentially copy a to b without having to specify the size of b.
How can I do this in cpp?
There is no assignment operator overload for plain arrays. You have to use some copy function like this:
char a[] = "abc";
decltype(a) b;
std::copy( std::begin(a), std::end(a), std::begin(b) );
Using decltype we get the type of array a and use that to declare array b.
But this is still not very C++ish in my opinion.
As commenters suggested, simply use std::string. If you can't use std::string please explain why.
std::string a = "abc";
std::string b = a;
Much cleaner and less things that can go wrong.
/ sizeof(a[0]) since sizeof(char) is guaranteed to always be one. That said it does make it less brittle if the type ever changes.decltype(a) b; instead of char b[sizeof(a)/sizeof(a[0])];
char a[]in this case is a character array. If you need just one char then you can writechar a = 'a';std::string b = a;makes the whole nightmare go away.std::stringor some other container class that has=overloaded to do such copying.std::array.int[10]is an array of 10ints. You can obtain the size of a C array using the ratio between thesizeofthe array and thesizeofan element. You can also obtain it through template deduction. C arrays decay easily and frequently to pointers, but they are clearly distinct types. Having said that, please to not take this comment as encouragement to use of C arrays where safer and more powerful alternatives exist.charthat's terminated by a nul character. Functions that take C strings treat that terminator as the end of the string. A string literal such as"abc"is an array ofconst char; it contains the characters between the quotes and a nul terminator, so it Can be used as a C string. Achararray will have a nul terminator if you put one in it, and won't if you don't. If it has a nul terminator it can be used as a C string; if it doesn't, it can't.