1

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.

j_mcnally
  • 6,928
  • 2
  • 31
  • 46
  • dbentry* track = new dbentry(...); – Matthew Beck Oct 08 '12 at 04:40
  • Its `return track;` Hope the `*` is a typo. What do you mean by not working ? What does the function `getFieldForMarker` do ? – Mahesh Oct 08 '12 at 04:40
  • how can you use dbentry * track? It has not been allocated and points to some random memory location. (Obviously i was too slow with posting) if you really want a struct it would be declared as "struct dbentry * varName = (struct dbentry *) malloc(sizeof(dbentry)) – Oliver Oct 08 '12 at 04:41

1 Answers1

4

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;
Kirill Kobelev
  • 10,252
  • 6
  • 30
  • 51
Toribio
  • 3,963
  • 3
  • 34
  • 48
  • Of course, you have to do a `delete test;` after the `cout` statement to avoid memory leaks. Or better yet, use a `unique_ptr`, or possibly even return the structure itself. – In silico Oct 08 '12 at 04:47
  • yeah this works great! thank you, sorry im new to this stuff. some of it was syntax, but i see what u mean about the memory allocation. *facepalm* – j_mcnally Oct 08 '12 at 04:47
  • just out of curiousity how do i write the deconstructor for a struct? is it just like a class? – j_mcnally Oct 08 '12 at 04:50
  • @j_mcnally Yeah, it's the same. Same for constructors as well. – M4rc Oct 08 '12 at 04:56
  • @j_mcnally: Also have a look at [this answer](http://stackoverflow.com/a/3431492/1085062) – Rody Oldenhuis Oct 08 '12 at 04:57