IanHacker IanHacker - 3 months ago 13
C Question

What's wrong with the definition?

I'm trying to compile "libsamplerate.dll" with Visual Studio VC++ 2015 on Windows10, referring to: http://www.mega-nerd.com/SRC/win32.html.

Then, I got the following errors:

termination_test.c
.\tests\termination_test.c(82): error C2057: expected constant expression
.\tests\termination_test.c(82): error C2466: cannot allocate an array of constant size 0
.\tests\termination_test.c(82): error C2133: 'in': unknown size
.\tests\termination_test.c(83): error C2057: expected constant expression
.\tests\termination_test.c(83): error C2466: cannot allocate an array of constant size 0
.\tests\termination_test.c(83): error C2133: 'out': unknown size
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\cl.exe"' : return code '0x2'


"termination_test.c" is originally from:
http://www.mega-nerd.com/SRC/download.html
and here is the function which causes the errors:

static void
simple_test (int converter)
{
int ilen = 199030, olen = 1000, error ;

{
float in [ilen] ;
float out [olen] ;
double ratio = (1.0 * olen) / ilen ;
SRC_DATA src_data =
{ in, out,
ilen, olen,
0, 0, 0,
ratio
} ;

error = src_simple (&src_data, converter, 1) ;
if (error)
{ printf ("\n\nLine %d : %s\n\n", __LINE__, src_strerror (error)) ;
exit (1) ;
} ;
} ;

return ;
} /* simple_test */


I simply modified these two lines to:

float in [199030] ;
float out [1000] ;


... then, worked perfectly.

However, what's wrong with the definition?

int ilen = 199030, olen = 1000, error ;


I put 'const' in front of int, then I got another error "C2166: l-value specifies const object".
How can I make it error-free?

(P.S., This is an open-source code, so there shouldn't be any errors. This isn't a question, but I just wonder why.)

Answer

Continuing from the comment, the subtle point you were missing is that in C, array declaration requires a constant expression for the array size (e.g. array[CONST]). fn1. When you declare:

int ilen = 199030, olen = 1000, error ;

Neither ilen or olen are constant expressions. (the easy way to think about it is you could easily do ilen = ilen + 2; -- so ilen isn't a constant expression.)

Constant expressions are generally created by #define or enum (which create global constants). (and you generally CAPITALIZE constants -- just to distinguish then from other variables). So you could do:

#define ILEN 199030
#defile OLEN 1000

or

enum { OLEN = 1000, ILEN = 199030 };

and then declare your float arrays:

float in [ILEN],
     out [OLEN];

fn 1. Modern C compilers allow allow the use of the variable length array which can be declared in the way you have attempted, but as others have pointed out, your compiler does not support VLAs.

Comments