开发者

structure programme

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];


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’


You should use dynamic allocation. I think this is exactly what you want: http://fydo.net/gamedev/dynamic-arrays

Regards


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜