variable for array ?

This is a discussion on variable for array ? within the C++ Programming forums, part of the General Programming Boards category; hi all~ i remembered one-dimentional array requires const as argument when it was established but now i can pass variable ...

  1. #1
    flashing vampire black's Avatar
    Join Date
    May 2002
    Posts
    563

    variable for array ?

    hi all~

    i remembered one-dimentional array requires const as argument when it was established but now i can pass variable to it ? i update Dev-C++ not long ago i wonder whethere it was exception of Dev-C++ compiler, my code is right below:
    Code:
    int main()
    {
        int n = 10;
        int arr[n];    // No error occured !!!
        return 0;
    }
    any ideas ?
    Never end on learning~

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    Some compilers have an extension that allows non-constant array sizes. You can use it, but your code won't be portable. The standard way to do this is with dynamic memory allocation:
    Code:
    int
    main()
    {
      int  n = 10;
      int *arr = new int[10];
    
      ...
    }
    But of course, the standard library should be preferred over ad hoc code:
    Code:
    #include <vector>
    
    int
    main()
    {
      int              n = 10;
      std::vector<int> arr(n);
    
      ...
    }
    My best code is written with the delete key.

  3. #3
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,630
    That's valid in C99 and is enabled by default as a compiler extension in GCC.

    Ref: http://gcc.gnu.org/onlinedocs/gcc-3....iable%20Length

    gg

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question about printing a variable???
    By Hoser83 in forum C++ Programming
    Replies: 2
    Last Post: 03-31-2006, 12:57 PM
  2. How accurate is the following...
    By emeyer in forum C Programming
    Replies: 22
    Last Post: 12-07-2005, 11:07 AM
  3. Replies: 2
    Last Post: 04-12-2004, 01:37 AM
  4. write Variable and open Variable and get Information
    By cyberbjorn in forum C++ Programming
    Replies: 2
    Last Post: 04-09-2004, 01:30 AM
  5. Variable question I can't find answer to
    By joelmon in forum C++ Programming
    Replies: 3
    Last Post: 02-12-2002, 03:11 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21