2013-03-19 57 views
0

该代码与过滤_video.c(ffmpeg doc中的一个示例代码)几乎相似。为什么AVFormatContext指针在非全局结构对象中初始化,而在全局对象中是NULL?

在原始示例文件中,有许多全局静态变量。这里是第一个版本的代码的一个片段(原来一样的样品):

static AVFormatContext *fmt_ctx; 
static AVCodecContext *dec_ctx; 

int main(int argc, char **argv) { 

// .... other code 
    if ((ret = avformat_open_input(&fmt_ctx, filename, NULL, NULL)) < 0) { 
     av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n"); 
     return ret; 
    } 

// .... other code 

} 

由于所有这些变量充当了打开一个视频文件,我宁愿他们组。所以我的代码的目的是重新排列这些变量,使源文件更加结构化。

我想到的第一个想法是使用结构。

struct structForInVFile { 
    AVFormatContext *inFormatContext; 
    AVCodecContext *inCodecContext; 
    AVCodec* inCodec; 
    AVPacket inPacket; 
    AVFrame *inFrame; 
    int video_stream_index; 
    int inFrameRate; 
    int in_got_frame; 
}; 

现在的代码的第二版就变成了:

int main(int argc, char **argv) { 

// .... other code 
structForInVFile inStruct; 

    if ((ret = avformat_open_input(&inStruct.inFormatContext, filename, NULL, NULL)) < 0) { 
     av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n"); 
     return ret; 
    } 

// .... other code 

} 

结果为第2版:代码不能在avformat_open_input工作。没有错误信息。该程序默默退出。 通过调试,我发现:inStruct.inFormatContext:0xffffefbd22b60000

在第三版的代码中,我将inStruct设置为全局变量。 代码变为:

structForInVFile inStruct; 

int main(int argc, char **argv) { 

// .... other code 
    if ((ret = avformat_open_input(&inStruct.inFormatContext, filename, NULL, NULL)) < 0) { 
     av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n"); 
     return ret; 
    } 

// .... other code 

} 

第3个版本的结果:代码有效。 通过调试,我发现:inStruct.inFormatContext:0x0

所以我认为原因是:AVFormatContext应该零初始化为avformat_open_input工作。 现在,问题是:

为什么AVFormatContext指针在非全局结构对象中初始化,而在全局对象中初始化为零?

我不知道作为全局变量或非全局变量的结构对象的定义有什么区别。

回答

2

简单。根据C++标准3.6.2初始化非本地对象的:

具有静态存储的持续时间(3.7.1)的对象应是零初始化(8.5)的任何其它初始化发生之前。

备注:您的问题重复。请在查询之前仔细搜索StackOverflow。

+0

谢谢。我搜索了一下,并查看了C++素数。但我认为我没有找到好的关键字来搜索正确的页面。 – user1914692 2013-03-20 00:14:52