Reputation: 1
i am not able to run my structure programme. as it is getting an "constant expression required" error. in this line:
struct book_info book[i];
Upvotes: 0
Views: 134
Reputation: 214495
In the old C standard (C89) you could only set array length with a "constant numeric literal", ie
int array[100];
or
#define X 100
int array[X];
In the new C standard (C99) the same applies if the variable is allocated at file scope (global). But if the array is allocated at local scope (inside a function), then C99 allows you to use a non-constant value as in your example.
Upvotes: 0
Reputation: 6392
You should use dynamic allocation. I think this is exactly what you want: http://fydo.net/gamedev/dynamic-arrays
Regards
Upvotes: 0
Reputation: 882146
You are almost certainly using a compiler (or a compiler mode) that does not support variable length arrays.
The ability to declare variable length arrays (VLAs) was added to C99 so, if your compiler doesn't comply with the standard, or you're compiling with something like gcc -std=c89
, it won't work.
For example:
pax$ cat qq.c
#include <stdio.h>
#include <string.h>
int main (void) {
int i = 7;
char x[i];
strcpy (x, "xyz");
printf ("%s\n", x);
return 0;
}
pax$ gcc -std=c99 -pedantic -Wall -o qq qq.c ; ./qq
xyz
pax$ gcc -std=c89 -pedantic -Wall -o qq qq.c
qq.c: In function ‘main’:
qq.c:5: warning: ISO C90 forbids variable length array ‘x’
Upvotes: 4