Boris Raznikov
Boris Raznikov

Reputation: 2453

memcpy_s C++ pointer

I have a question using memcpy_s.

std::vector<char> MyBuf;   
MyBuf.resize(10);

char* p = &MyBuf[0];

Now I want to copy using memcpy_s to the data of the vector using the pointer p.

memcpy_s(XXXXX, 10, "BOBBO", 5);

What do I need to enter instead of XXXXX?

When using &p[0] instead of XXXXX I get a memory exception.

Upvotes: 1

Views: 3294

Answers (3)

unwind
unwind

Reputation: 399881

  1. If using C++11, don't use &MyBuf[0];, use MyBuf.data() instead.
  2. The pointer to use is p.
  3. Copy one character more if you want the destination to be usable as a string, you're missing the terminator.

Upvotes: 5

Mikhail
Mikhail

Reputation: 21769

Use std::copy instead. It is faster and safer.

const char* str = "BOBBO";
std::copy(str, str + sizeof(str), MyBuf.begin());

Upvotes: 1

Juraj Blaho
Juraj Blaho

Reputation: 13461

Use MyBuf.data() as a destination pointer if you have C++11 standard library. Using &MyBuf[0] should work, but is unnecessarily ugly.

Upvotes: 0

Related Questions