简体   繁体   English

在C中返回一个指针

[英]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: 编辑:添加tTblVideo定义:

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

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

} tTblVideo;

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. 这表明table->data[i]应该是指向具有mediaID成员的结构的指针。 However, the return statement is dereferencing this pointer, meaning it would return a structure object, not a pointer to a structure. 但是, return语句取消引用此指针,这意味着它将返回结构对象,而不是结构的指针。 Based on this, I would say you should not dereference the value to the return : 基于此,我想说您不应该将值取消引用到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 . 但是,您对tTblVideotypedef显示data成员是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];

table->data is of type tVideo* , so table->data[i] is of type tVideo . tVideo* table->data的类型为tVideo* ,因此tVideo* table->data[i]的类型为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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM