Warning 'Variable lenght arrays in C++ are a Clang extension'
-
Hi everyone,
I have a compiler warning about the length of an array which cannot be a variable.
My problem is that this length depends on the number of lines in a file, which I don't know in advance.
I thought that reassigning this variable to a constant would solve the warning problem, but this isn't the case.Would you have a solution, other than using a vector, as this option - which I've already explored - doesn't suit me, and I'd like to keep using an array.
Thanks in advance!
The code for the methods concerned :
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Création d'un Tableau 2D pour les 'Fixes' du fichier '_user_nav.dat' void ApprochWindow::createTableauFixes() { // Création -si elle n'existe pas déjà- de l'arborescence des fichiers utilisés et créés par Procedures4XP QDir().mkpath(QDir::homePath() + "/Documents/Procedures4XP/source files"); QString fichier = QDir::homePath() + "/Documents/Procedures4XP/source files/_user_fix.dat"; QFile file(fichier); // Appel du constructeur de la classe QFile if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { QMessageBox::information( this, tr("Fichier '_user_fix.dat' non trouvé"), QString(tr("Le fichier 'user_fix.dat' définissant les Waypoint personnalisés \n " "n'a pas été trouvé ! \n" " Certaines fonctionnalités ne seront donc pas actives.")), QMessageBox::Ok ); return; // sortie de la MÉTHODE } // Comptage des lignes du fichier // CODE 1 QString ligne; int nbrLignes = 0; while (!file.atEnd()) { ligne = file.readLine(); nbrLignes ++; } qDebug() << "Le fichier _user_fix.dat comporte " << nbrLignes << " lignes"; const int NBLINES = nbrLignes; // NBLINES ne sera pas considérée comme une constante :-( // CODE 2, inefficace également pour créer une constante //const int NBLINES = compterLignes(&file); // Définition du tableau qui recevra les données de 'user_fix.dat' QString tabFix[NBLINES][7]; QTextStream Flux_lu(&file); QString Mot_lu = ""; // Retour au début du fichier, après comptage du nombre de lignes file.seek(0); // Pour les 'NBLINES' lignes du formulaire, d'indice 0 à NBLINES-1 ... for (int l = 0; l < NBLINES ; l++) { // ... et les 7 colonnes d'indice 0 à 6 for (int c = 0; c < 7 ; c++) { // Un mot est lu à chaque boucle, et est placé en variable Mot_lu Flux_lu >> Mot_lu; // Remplissage du tableau 2D tabFix[l][c].insert(0,Mot_lu); // Sortie de la boucle en fin de fichier if (Flux_lu.atEnd()) break; } } file.close(); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Comptage du nombre de ligne int ApprochWindow::compterLignes(QFile* fichier) { QString ligne; int nombreLignes = 0; while (!fichier->atEnd()) { ligne = fichier->readLine(); nombreLignes ++; } qDebug() << " Via 'compterLignes()', le fichier '_user_fix.dat' comporte " << nombreLignes << " lignes"; const int NBL = nombreLignes; return NBL; }
-
@MortyMars said in Warning 'Variable lenght arrays in C++ are a Clang extension':
I have a compiler warning about the length of an array which cannot be a variable.
Yes, that's the issue or better "warning"... VLA's are not standard C++ language (
anymore, or never were?!... anyway it's plain C style).My problem is that this length depends on the number of lines in a file, which I don't know in advance.
Then keep it dynamic?!
I thought that reassigning this variable to a constant would solve the warning problem, but this isn't the case.
The code you show above doesn't change anything, because the same old variable - which is unknown at compile time - is assigned to your
const int
. Same problem.Better use
QList<QString>
orQVector<QString>
andreserve
the memory +resize
your containerthis option - which I've already explored - doesn't suit me, and I'd like to keep using an array.
For what reason a C array suits your use case more than the Qt container classes?!
Edit:
Just discovered that you are even using a 2D array...
There are such things asstructs
, for example :))
You could store one dimension in there and then use a 1-dim container with your struct. -
@Pl45m4 said in Warning 'Variable lenght arrays in C++ are a Clang extension':
anyway it's plain C style).
no, vla's are not C - it's a clang/gcc extension.
change
const int NBLINES
toconstexpr int NBLINES
so it's a normal array or even better - use a proper container (std::array). -
Thank you both @Pl45m4 and @Christian-Ehrlicher for your help ;-)
There is therefore no mechanism for defining a CONST by giving it the value of a variable (at some point in its life) :-(
Is there a way of telling the compiler to ignore this warning?
-
@MortyMars I wrote what you have to change.
-
As far as the standards go, the size of everything that is allocated on the stack must be known at compile time. Various vendor extensions (and the C99 revision of the C standard, which has since deprecated it) allow breaking this rule for local arrays. This is generally perceived to be a bad idea, and should avoided, because:
- Stack space is typically more limited relative to the heap, allocating large arrays on the stack will increase chance of a stack overflow.
- It makes it harder for the compiler to verify that all reads and writes of local variables happen within the current stack frame. Writing outside of the frame (especially when it is guided by user input) is an extremely serious security vulnerability, and often a component in privilege escalation exploits.
So yes - you really should allocate anything that you don't know the size of ahead of time on the heap, and ideally in a managed container. I'm not sure why a vector won't do for you - wanting a 2D array isn't an excuse, you can do a vector of vectors, a vector of structs, or allocate sufficient space and treat the one vector's data pointer as a row-by-row 2D array.
-
@IgKh said in Warning 'Variable lenght arrays in C++ are a Clang extension':
size of everything that is allocated on the stack must be known at compile time
Just for the record, I don't see any evidence that the OP's code is inside any function or allocated on the stack. It might be, but it might just as well not be. If it is "global" scope (or for that matter class variables where no instance is ever stack-allocated) you still need to use
constexpr
(or equivalent) and not justconst
, because it needs to be a constant and not a variable, right? -
@JonB In OP's provided source code, they have in their
ApprochWindow::createTableauFixes
method:// Définition du tableau qui recevra les données de 'user_fix.dat' QString tabFix[NBLINES][7];
This is definitely a stack allocation. But you are probably right - I don't believe that even globals and statics are allowed to be unsized in C++, if only for the technical reason that the linker needs to know how big the data segment is at link time at the very latest.
-
@IgKh
I only looked at the 2-line screenshot :)And I don't think it's just a linker issue, it's a compiler one too. If you have, say in a class or for that matter on the stack,
int array[non_constexpr_size]; int next_variable;
I don't think the compiler can even generate code since it does not know the offset of
next_variable
at compile-time. Or perhaps they figure a way because it's an optional "extension", but I can see the problem.I don't mean to be on your case! What you said is good. It's just that there are lots of/complex reasons why "vanilla" C/C++ has this restriction.
-
@Christian-Ehrlicher said in Warning 'Variable lenght arrays in C++ are a Clang extension':
I wrote what you have to change.
I obviously paid attention to your message and immediately tried out the suggested code.
Unfortunately I don't get a ‘warning’ any more, but an ‘error’ preventing me from going any further.Unless there's something else behind your answer, which I didn't understand... ?!
-
@MortyMars
Like it says, aconstexpr
must be assigned/set to a constant value, like10
. Assuming yournbrLignes
is some variable it is not acceptable. It does not matter which way up you look at it/try to do it, you cannot declare an array with a size which is ultimately a variable, as per previous discussions.In a word, if
nbrLignes
orNBLINES
or anything else is not a constant you cannot use it for the size of a plain array, because they require a fixed, constant size. You couldnew
an array with a variable size, or you could use some non-fixed-size container such asstd:array
orQList
/QVector
if you want variability, but not a plain C-type likearray[SIZE]
as a local or global variable. -
@IgKh said in Warning 'Variable lenght arrays in C++ are a Clang extension':
you can do a vector of vectors, a vector of structs, or allocate sufficient space and treat the one vector's data pointer as a row-by-row 2D arrayThank you ... for your help.
Thank you @IgKh for your help
As I said, I tried the vector of vectors solution, but I wasn't able to manage the matrix created, both in writing and reading the data, without running into access errors that prevented compilation.
Furthermore, as I see it, a 2D array seems (wrongly, it seems) to be more appropriate.
But I'm not definitively rejecting the idea of returning to vectors...
-
@JonB said in Warning 'Variable lenght arrays in C++ are a Clang extension':
I don't mean to be on your case! What you said is good. It's just that there are lots of/complex reasons why "vanilla" C/C++ has this restriction
Thank you @JonB for these very clear explanations, even if I'm beginning to realiseund that I'm going to have to reconsider my choice of a 2D array... :-(
-
@MortyMars said in Warning 'Variable lenght arrays in C++ are a Clang extension':
As I said, I tried the vector of vectors solution, but I wasn't able to manage the matrix created, both in writing and reading the data, without running into access errors that prevented compilation.
Then you need to correct that. Code using vector-of-vector can be addressed just as much/in same way as array-of-array.
Vector-of-vector seems just as suitable as array-of-array for a two-dimensional array/container. (Assuming you are "in charge" of the data structure, not trying to make your structure correspond to something received from the outside world in a particular layout format.)
You can use an array-of-array, effectively, if that is what you want. You just cannot declare it as
array[variable][variable]
. You can do it e.g. withnew
s and/or making it more likeQString **array
per the old C way. But I think people would recommend e.g. astd::array
ofstd::array
. -
@MortyMars I see how one can struggle with a vector of vectors, since you have to resize every element of the outer array prior to use.
But, since one dimension is dynamically size, and one isn't, you can mix and match to improve ergonomics.
Consider declaring
tabFix
as:std::vector<std::array<QString, 7>> tabFix; tabFix.resize(nbrLignes);
This pre-allocates 7 empty QStrings for each line at runtime, so you access it just like a 2D array.
-
@JonB said in Warning 'Variable lenght arrays in C++ are a Clang extension':
Vector-of-vector seems just as suitable as array-of-array for a two-dimensional array/container. (Assuming you are "in charge" of the data structure, not trying to make your structure correspond to something received from the outside world in a particular layout format.
So I'm going to try my luck again with the vector-to-vector solution that I'd abandoned.
And I'll take the liberty of asking you again to correct my code as I go along... ;-)Thanks again to everyone in the meantime.
-
@IgKh said in Warning 'Variable lenght arrays in C++ are a Clang extension':
Consider declaring tabFix as:
std::vector<std::array<QString, 7>> tabFix;
tabFix.resize(nbrLignes);
This pre-allocates 7 empty QStrings for each line at runtime, so you access it just like a 2D arrayA huge thank you @IgKh
Your solution, which is a good compromise between what the community plebiscites and my personal stubbornness, works perfectly!!!!
No more error messages and even fewer errors, while still accessing my data naturally (IMHO).
-
M MortyMars has marked this topic as solved on