期望的持续表达

时间:2013-10-06 15:38:05

标签: c arrays

我们有一段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

2 个答案:

答案 0 :(得分:5)

Uint8 process_buf[waveleft];

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

假设编译器仍然是Visual Studio,您可以动态分配process_buf

答案 1 :(得分: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)。