Array question

This is a discussion on Array question within the C++ Programming forums, part of the General Programming Boards category; I want to have a 2 dimensional array thats size is determined by user input. I want to do something ...

  1. #1
    Registered User Bad_Scooter's Avatar
    Join Date
    Mar 2003
    Posts
    15

    Array question

    I want to have a 2 dimensional array thats size is determined by user input. I want to do something like this: (declaration)

    int array [x] [y];

    where x and y are input by the user. But how would I declare this? If I try it like above it tells me constant expected. Any help would be great. Thanks.

  2. #2
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    You need dynamic allocation using new[]/delete[] or to use a container like std::vector.
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  3. #3
    Registered User Bad_Scooter's Avatar
    Join Date
    Mar 2003
    Posts
    15
    Vectors would be a lot easier, I agree, but I'm doing a project that doesn't allow them. I'm not familar with the other method you mentioned. I'm going to look around and see what I can find on it, but if you wouldn't mind elaborating that would be great.

  4. #4
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    Essentially, you'll have something like this:
    Code:
    int** array;
    array = new int*[x];
    for(int i = 0; i < x; ++i)
        array[i] = new int[y];
    
    // Use and delete.
    
    for(int j = 0; j < x; ++j)
        delete[] array[j];
    delete[] array;
    Look into pointers and dynamic memory allocation. 'new' allocates a block of memory, and then returns a pointer to it. 'delete' gives that block of memory back.
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dynamic Mutli dimensional Array question.
    By fatdunky in forum C Programming
    Replies: 6
    Last Post: 02-22-2006, 06:07 PM
  2. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  3. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  4. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  5. array question?
    By correlcj in forum C++ Programming
    Replies: 1
    Last Post: 11-08-2002, 05:27 PM

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