1

While I'm trying to explore possibilities of arrays in C in ANSI, I'm confronted with an issue. Here's my code:

#include <stdio.h>
#include <string.h>

static int MAXLIGNE = 5000;
char *ptrlig[MAXLIGNE]; // PTR SUR LA LIGNE DE TXT // GOT AN ISSUE : 
                        // VARIABLY MODIFIED PTRLIG @ FILESCOPE

int lirelignes(char *ptrlig[], int nlignes);
void ecrirelignes(char *ptrlig[], int nlignes);
void trirapide(char *ptrlig[], int gauche, int droite);

Error from the GCC :

VARIABLY MODIFIED PTRLIG at FILESCOPE

I've seen that 'const' type may create that kind of issues. I tried to make it like :

#include <stdio.h>
#include <string.h>

static int MAXLIGNE = 5000;
unsigned char *ptrlig[MAXLIGNE];

But that doesn't seem to change anything in this case.

Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229
  • When you say "ANSI C", do you mean C89 (equivalent to Standard C from ISO, C90), or do you mean 'Standard C' — probably C11 or perhaps C18, depending on how modern your compiler is? If your answer is "I've no idea what you're talking about", then the chances are you're actually using a compiler capable of working with C11 (use `-std=c11` or `-std=gnu11`), and should use that instead of `-ansi` (which means `-std=c90`). C90 did not support variable length arrays at all; C99 does support them, but they must defined within a function; C11 provides conditional support for variable length arrays. – Jonathan Leffler Aug 23 '18 at 00:23
  • Hey ! I'm talking about C89, but my compiler is definitely c11. I'm using the K&R book but indeed, i may use a C90 compiler, not dumb.. shame on me ! – Sarah Connorh Aug 23 '18 at 02:37

1 Answers1

3

The length of an array defined at file scope must be a compile time constant, and the value of another variable does not qualify as such.

If you want to use a name for the length of this array, you'll need to use a macro:

#define MAXLIGNE 5000
char *ptrlig[MAXLIGNE]; 

The macro does a direct text substitution, so after the preprocessor stage it is the same as char *ptrlig[5000];

dbush
  • 186,650
  • 20
  • 189
  • 240
  • Or an `enum` — see also [`static const` vs `#define` vs `enum`](https://stackoverflow.com/questions/1674032). – Jonathan Leffler Aug 23 '18 at 00:09
  • Hey thx for answer me. I tried to use it, but also (may be the compiler c11 that doesnt support this macro) i can't create this macro :/ PS : enum worked but i want to understand why the rest doesnt. – Sarah Connorh Aug 23 '18 at 02:40
  • @SarahConnorh The above should work. If it doesn't then you must have mistyped something. – dbush Aug 23 '18 at 02:42
  • @dbush Yes but using macro. I wanted to use a more local variable this macro is accessible only on one file and callable from everyfunction.. – Sarah Connorh Aug 23 '18 at 18:03