tomacco
tomacco

Reputation: 23

Returning a pointer in C

this is the first time I ask here. I just wanted to know if the "returns" of this block of code are correct, specially the first one.

tVideo* getVideo(int id, tTblVideo* table){
    tVideo* videoFound = NULL;
    int i;
    for(i = 0; i < table->length; i++){
        if(table->data[i]->mediaID == id) return *table->data[i];
    }
    return videoFound;
}

EDIT: Adding tTblVideo definition:

typedef struct {
    /* Number of stored files */
    int length;

    /* Array of video files */
    tVideo *data;

} tTblVideo;

Upvotes: 2

Views: 172

Answers (2)

ams
ams

Reputation: 25559

table->data is of type tVideo*, so table->data[i] is of type tVideo. To return a pointer to the array entry you need to take the address of that entry:

if(table->data[i].mediaID == id) return &table->data[i];

Upvotes: 1

jxh
jxh

Reputation: 70382

From this line of code:

    if(table->data[i]->mediaID == id) return *table->data[i];

This shows that table->data[i] is expected to be a pointer to a structure with a mediaID member. However, the return statement is dereferencing this pointer, meaning it would return a structure object, not a pointer to a structure. Based on this, I would say you should not dereference the value to the return:

    if(table->data[i]->mediaID == id) return table->data[i];

However, your typedef for tTblVideo shows that the data member is a pointer to tVideo. Your function would not compile. Minimal fixups would be to use the right structure member access operator, and return the address of the found element.

    if(table->data[i].mediaID == id) return &table->data[i];

Upvotes: 3

Related Questions