j_mcnally
j_mcnally

Reputation: 6958

Return a pointer to a structure from a function

I am trying to return a pointer to my structure from a function:

dbentry* FileReader::parseTrack(int32_t size, char *buffer) {
  dbentry* track;
  int cursor = 0;
  //parse relevant parts
  track.title = this->getFieldForMarker(cursor, size, "tsng" , buffer);
  return track;
}

setting title is obviously not working but i don't know what to do, also how would i read a value from the pointer, ive tried some casting but nothing seems to work, most of what i found i couldn't figure out how to apply, or it was for C.

Upvotes: 1

Views: 271

Answers (1)

Toribio
Toribio

Reputation: 4078

You didn't allocate the structure memory, thus you're accessing and returning no memory address. You would need something like this:

dbentry* FileReader::parseTrack(int32_t size, char *buffer)
{
    dbentry* track = new dbentry;
    int cursor = 0;
    //parse relevant parts
    track->title = this->getFieldForMarker(cursor, size, "tsng" , buffer);
    return track;
}

Note that you have to return the structure pointer, so you don't want to dereference the pointer in its return, so just use return track; instead of return *track;.

The reason for this is that track is already a pointer. You would return the pointer of a pointer in your original solution.

So you would use the function like this:

dbentry* test = something->parseTrack(size, buffer);
std::cout << test->title;
delete test;

Upvotes: 3

Related Questions