Peter111
Peter111

Reputation: 823

C++ Invalid conversion from char* to char (char* = *string.begin() )

I've got the following code:

std::string extract() {

    fstream openfile("/home/name/Documents/testfile");
    std::string teststring;
    long location = 4;
    long length = 2;
    teststring.resize(length);
    char* begin = *teststring.begin();
    openfile.seekp(location);
    openfile.read(begin, length);

    return teststring;
}

This code is supposed to return a string of the characters found in a file. For example if the content of the file is

StackOverflow

this method should return

kO

This code was given to me by a friendly StackOverflow User. My problem is, that I get a Compile Error which says: "Invalid Conversion from char* to char". The problem is the

char* begin = *teststring.begin();

line. How can I fix this?

Upvotes: 4

Views: 849

Answers (2)

Jts
Jts

Reputation: 3527

teststring.begin() returns an iterator, and if you dereference it with the * operator, you get a reference to a char (char&).

Therefore, you can take it's address like:

char* begin = &*teststring.begin();

Or you can just do:

char* begin = &teststring[0];

Or

char* begin = &teststring.front() //(C++11) [@Jonathan Wakely]

The same thing goes for vectors. Altho in vector (C++11) a new function called data() was added which returns a pointer to T;

so with a vector you could just do

char * begin = myvector.data(); // (if T is char)

Upvotes: 5

Captain Giraffe
Captain Giraffe

Reputation: 14705

If you want to convert the iterator value to the underlying data there is a trick to get the pointer to the first element.

auto iterator_testdata = testdata.begin();
char* first_element_in_testdata = &(*iterator_testdata);

Provided the iterator iterates char values.

This trick also works for vector::begin() and similar continuous containers. Use with care.

Upvotes: 1

Related Questions