CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Feb 2003
    Posts
    21

    const int and delcaration of an array

    I'm writing a program and it has to do with an array. I have to let the user decide the size of the array,but when I code this,
    int combined;
    cin >> combined;
    const int SIZE= combined;
    int array[SIZE];
    the compiler gives me an error. I also tried this
    const int SIZE;
    cin >> SIZE;
    int array[SIZE];
    How can I declare and array of a size decided by the user?

  2. #2
    Join Date
    Oct 2002
    Location
    Singapore
    Posts
    3,128
    Since the size is varying, you can't create the array on the stack. Try using "new" instead.

    int size;
    cin >> size;

    int* array = new int[size];

    delete []array;

  3. #3
    Join Date
    Feb 2003
    Posts
    21
    THank you so much. It worked!

  4. #4
    Join Date
    Oct 2002
    Location
    Singapore
    Posts
    3,128
    You're welcome.

  5. #5
    Join Date
    Apr 1999
    Posts
    27,449

    Re: const int and delcaration of an array

    Originally posted by SGSpecialK
    I'm writing a program and it has to do with an array. I have to let the user decide the size of the array,but when I code this,
    int combined;
    cin >> combined;
    const int SIZE= combined;
    int array[SIZE];
    the compiler gives me an error. I also tried this
    const int SIZE;
    cin >> SIZE;
    int array[SIZE];
    How can I declare and array of a size decided by the user?
    Code:
    #include <vector>
    #include <iostream>
    using namespace std;
    //...
    int nSize;
    cin >> nSize;
    vector<int> array( nSize );  // declare an array with variable size
    To declare a dynamic array in C++, you always go for the vector<> class unless you have a compelling reason to use new[] and delete[].

    Regards,

    Paul McKenzie

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured