Menu

Dynamic Arrays

2002-11-26
2012-09-26
  • Nobody/Anonymous

    I've tried to declare an int-array dynamically like

    int n;
    cin >> n;
    int array[n];

    and it WORKED! According to the standard it should not and I had to use array = new int[n].
    In C++ Builder and Visual C++ it really does not work. Why in Dev?

     
    • Nobody/Anonymous

      The question is more correctly phrased "Why in gcc", since Dev is just a front end for gcc...

      Wayne

       
    • Nobody/Anonymous

      Interestingly enough, it compiles on gcc-3.2.3 on Cygwin, but when run, it core dumps.

      :-)

      Wayne

       
    • Matt Fiedler

      Matt Fiedler - 2002-11-27

      On Mingw 2.95.3, it both compiles and works as "expected"!  I say expected in quotation marks, because I would expect a crash, but that does not occur.  I don't understand; this is not supposed to work!

      Matt Fiedler

       
      • Nobody/Anonymous

        Just because you overwrite an array (block of memory) it does not mean that your program will crash. It depends on what the compiler puts after the array. If you have important code after the array then the program will crash.

        BlakJak :]

         
    • Nobody/Anonymous

      True, I love out of bounds conditions!

      ;-)

      Wayne

       
    • Nobody/Anonymous

      Did I mention I have seen test flights crash and burn because of out-of-bounds conditions.  In Ada even.  Turned out to get throughput they needed, they had to compile with range checking suppressed.  Turned out the overage did slop into some important stuff.

      Ack, makes me sick to this day.  So I try to check my indices and dimension my arrays a slot or two bigger than I think I need.

      Boring, I know...

      Wayne

       
    • Anonymous

      Anonymous - 2002-11-27

      ...
      Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C89 mode and in C++. (However, GCC's implementation of variable-length arrays does not yet conform in detail to the ISO C99 standard.) These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the brace-level is exited. For example

      FILE *
      concat_fopen (char *s1, char *s2, char *mode)
      {
        char str[strlen (s1) + strlen (s2) + 1];
        strcpy (str, s1);
        strcat (str, s2);
        return fopen (str, mode);
      }

      Jumping or breaking out of the scope of the array name deallocates the storage. Jumping into the scope is not allowed; you get an error message for it.
      ....

      Taken from GCC documentation.

      Toni

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.