Replace strcpy

Flaviu_ 1,031 Reputation points
2022-04-21T09:37:19.01+00:00

I have the following code:

void test_func(const char(*str)[4])
{
    std::cout << *str << std::endl;
}

caller code:

std::string s{"abc"};
char c[4];
strcpy_s(c, s.c_str());
test_func(&c);

It is possible to replace char[4] with modern std::vector<char> ? If it is, how can I do that ?

I have tried a silly code:

std::vector<char> chars(s.cbegin(), s.cend());
test_func(&chars[0]);

Of course, didn't work it.

Developer technologies C++
{count} votes

Accepted answer
  1. RLWA32 49,536 Reputation points
    2022-04-21T11:50:36.07+00:00

    It's not safe but you could call the library function using a properly sized string s -

    test_func(reinterpret_cast<const char(*)[4]>(s.c_str()));
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.