1

我们有一段 C 代码如下。任何解决方案都已声明并初始化

void fillProcess(void *unused, Uint8 *stream, int len)
{
    Uint8 *waveptr;
    int waveleft=0;

    waveptr = wave.sound + wave.soundpos;
    waveleft = wave.soundlen - wave.soundpos;
    while ( waveleft <= len ) {
    /* Process samples */
    Uint8 process_buf[waveleft];
    SDL_memcpy(process_buf, waveptr, waveleft);
    /* do processing here, e.g. */
    /* processing the audio samples in process_buf[*] */
    // play the processed audio samples
    SDL_memcpy(stream, process_buf, waveleft);
    stream += waveleft;
    len -= waveleft;
    // ready to repeat play the audio
    waveptr = wave.sound;
    waveleft = wave.soundlen;
    wave.soundpos = 0;
    }
}

得到3个错误如下

Error   1   error C2057: expected constant expression   
Error   2   error C2466: cannot allocate an array of constant size 0    
Error   3   error C2133: 'process_buf' : unknown size
4

2 回答 2

5
Uint8 process_buf[waveleft];

此行使用可变长度数组,这是在 C99 中引入的。但是根据您的错误代码,您使用的是尚不支持 C99 的 Visual Studio。

假设编译器还是Visual Studio,可以process_buf动态分配。

于 2013-10-06T15:41:58.010 回答
2

使用 malloc 分配 process_buf:

void fillProcess(void *unused, Uint8 *stream, int len)
{
Uint8 *waveptr;
int waveleft=0;

waveptr = wave.sound + wave.soundpos;
waveleft = wave.soundlen - wave.soundpos;
    while ( waveleft <= len ) {
    /* Process samples */
    //Uint8 process_buf[waveleft];  // <-- OLD CODE
    Uint8 *process_buf = (Uint8 *)malloc(waveleft * sizeof(Uint8)); // <-- NEW CODE
    if(process_buf == 0) {
        // do something here
    }
    SDL_memcpy(process_buf, waveptr, waveleft);
    /* do processing here, e.g. */
    /* processing the audio samples in process_buf[*] */
    // play the processed audio samples
    SDL_memcpy(stream, process_buf, waveleft);
    stream += waveleft;
    len -= waveleft;
    // ready to repeat play the audio
    waveptr = wave.sound;
    waveleft = wave.soundlen;
    wave.soundpos = 0;
    // don't forget this:
    free(process_buf);  // <-- NEW CODE
    }
}

如果 malloc 失败并返回 0,您需要决定要做什么。可能终止程序。例如 fprintf(stderr) 和 exit(1)。

于 2013-10-06T15:56:25.303 回答