Liste des Groupes | Revenir à cl c |
I've found examples on the Net where the arrays have been defined in aYes, that would be a VLA.
function context and the size passed as parameter
f(int n) {
char * arr[n];
...
}
That reminded me on other languages where you'd need at least a blockBut a function body is in itself a block. Inside a function body you are already in "a block context".
context for dynamically sized arrays, like
int n = 5;
{
char * arr[n];
...
}
Anyway. I tried it without function or block contextYou mean you did this at file scope? No, VLAs are illegal at file scope. And I was unable to repeat this feat in GCC.
int n = 5;
char * arr[n];
...
and it seemed to work seamlessly like that (with GNU cc, -std=C99).
Q1: Is this a correct (portable) form?VLA objects have to be declared locally. However, keep in mind that support for local declarations of VLA _objects_ is now optional (i.e. not portable). Support for variably-modified _types_ themselves (VLA types) is mandatory. But you are not guaranteed to be able to declare an actual VLA variable.
Then, with above setting, I also triedYes. Since the beginning of times the language itself does not check/enforce array boundaries. When you violate the boundary, the behavior is undefined, meaning that compilers can do anything (including implementing array boundary checks, where possible). But for obvious performance reasons C compilers do not normally enforce array boundaries in "production" compilation modes.
arr[99] = "foobar";
To my astonishment the compiler did not only accept that but it also
operated without runtime error; but I assume it's an error that may
severely corrupt the memory. - Q2: Is my suspicion correct?
Les messages affichés proviennent d'usenet.