I want to have an array of char[maxname]
. My initial approach was the following
class char_list
{
char_list(int noc){names_.reserve(noc)}
std::vector<std::unique_ptr<char>> names_;
void setname( const char* name){ names_.push_back(name)};
}
When I try to invoke the routine by eg
char aux[100];
aux = 'asadsdsd'
const char* aux1 = aux;
setname(aux1);
I get the error
candidate function not viable: no known conversion from 'const char *' to
'const std::__1::__vector_base<std::__1::unique_ptr<char, std::__1::default_delete<char> >, std::__1::allocator<std::__1::unique_ptr<char, std::__1::default_delete<char> > > >::value_type' (aka
'const std::__1::unique_ptr<char, std::__1::default_delete<char> >') for 1st argument
_LIBCPP_INLINE_VISIBILITY void push_back(const_reference __x);
I am using clang
with C++17 standard.
In C++ you shall banish char[] and arrays in general. Normally you are expected to use std::vector and in the case of string, use std::string. Vector grows & shrink automatically and do memory management for you. std::string does the same but is specialized for string management.
So you code would look like:
std::vector<std::string> names;
Then you can do wonderful things like:
names.push_back("ABC");
And then you can easily retrieve your name:
std::string &name0 = names[0];
Or the char* equivalent(only for C interoperability):
const char *c_string = name0.c_str();
I want to have an array of char[maxname]
An array of arrays is called a 2-dimensional array.
constexpr unsigned N = 10; // 10 as an example.
char arr[N][maxname];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.