48

What is the easiest way of getting a char array from a vector?

The way I am doing is getting a string initialized using vector begin and end iterators, and then getting .c_str() from this string. Are there other efficient methods?

2 Answers 2

85

This was discussed in Scott Meyers' Effective STL, that you can do &vec[0] to get the address of the first element of an std::vector, and since the standard constrains vectors to having contiguous memory, you can do stuff like this.

// some function
void doSomething(char *cptr, int n)
{

}

// in your code
std::vector<char> chars;

if (!chars.empty())
{
    doSomething(&chars[0], chars.size());
}

edit: From the comments (thanks casablanca)

  • be wary about holding pointers to this data, as the pointer can be invalidated if the vector is modified.
Sign up to request clarification or add additional context in comments.

1 Comment

+1 but beware that the pointer may become invalid if the vector is modified later.
61
std::vector<char> chars;
char* char_arr = chars.data(); // &chars[0]

4 Comments

data() isn't part of the standard STL specification.
It is part of the new C++0x STL (implemented both in MVSC and GCC), and should be used over &chars[0] if your compiler supports it.
@ronag: Why should it be preferred? Just because of readability or do other reasons exist?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.