declaring an array of n elements based on input

This is a discussion on declaring an array of n elements based on input within the C++ Programming forums, part of the General Programming Boards category; the compiler complains about an integral constant for the array declaration. can it be done like this or do i ...

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    13

    declaring an array of n elements based on input

    the compiler complains about an integral constant for the array declaration.

    can it be done like this or do i have to use a pointer to set up the array ?

    i know this code is absolutely useless but i'd like to know for theoretical purposes.

    -----------------------------------------------------------------------------------
    void create(const int);

    main()
    {
    int size;

    cin << "Enter a number: " << size;

    create(size);

    return 0;
    }

    void create(const int max)
    {
    int array1[max];
    }

    -----------------------------------------------------------------------------------

  2. #2
    Registered User
    Join Date
    Sep 2001
    Posts
    85
    first error you have is your input/output. use cin >> only for input and cout<< for output

    cout<< "Enter a number: ";
    cin >> size;

    second error your function decleration does not match your function. change it to this:

    void create(const int max);

    the program with these changes will work, but the array will not be accessable from main, unless you declare the array in main. then you can pass a pointer or a reference of the array to the function.

  3. #3
    zen
    zen is offline
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    You can't have a static array based on a variable number of elements in standard C++ (it must be a compile time constant). Here are a couple of alternatives -

    Code:
    #include <vector>
    #include <iostream>
    
    using namespace std;
    
    
    int main() 
    { 
    	int size; 
    
    	cout<< "Enter a number: ";
    	cin >> size; 
    
    	//either
    
    	int* array1 = new int[size];
    	// do stuff
    	delete [] array1;
    
    	//or
    
    	vector<int> array2(size);
    
    	return 0; 
    }
    zen

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 05-29-2009, 08:25 PM
  2. Replies: 12
    Last Post: 04-12-2009, 06:49 PM
  3. Error with an array
    By SWAT_LtLen in forum C++ Programming
    Replies: 2
    Last Post: 03-29-2005, 11:00 AM
  4. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 08:48 PM
  5. Template Array Class
    By hpy_gilmore8 in forum C++ Programming
    Replies: 15
    Last Post: 04-12-2004, 12:15 AM

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