How to set size on an array post compile

Hello,
I'm new to this website and I am pretty excited to be a part of this community now.
I am taking my second course in c++ right now and I have this problem where i need to find a way to ask the user to input a number and that number will be set as the size of the array. I know i'm suppose to implement pointers in some way but i'm having trouble with it. Any tips?

void GetInfo(const int* numStudents)
{

const int *numStudents;
int y;
cout <<"enter amount of students:" << endl;
cin >> y;
numStudents = &y;
school[*numStudents];
//numStudents = school[];
schoolArrayInput(school, *numStudents);
}

Here is my code so far.
Sounds like you need to use dynamic memory, here a link below.

http://www.cplusplus.com/doc/tutorial/dynamic/

Also, I don't see that you have declared any arrays.
1
2
3
4
5
6
7
8
9
10
11
12
void GetInfo(const int* numStudents)
{

const int *numStudents;
int y;
cout <<"enter amount of students:" << endl;
cin >> y;
numStudents = &y;
school[*numStudents];
//numStudents = school[];
schoolArrayInput(school, *numStudents);
}

Line 4: numStudents has already been declared as an argument.
Line 9: Are you trying to declare any array? You need a type and a name. You have only one of the two (not sure which). Also, you can't declare any array with a variable.

PLEASE USE CODE TAGS (the <> formatting button). Code tags make it easier to help you.
Thanks for the help.

sorry I did not put the entire code up.
on line 9. school is the type i made using a structure. it contains 3 variables of type double.
I;m going to try to correct the code and see what happens.
closed account (zb0S216C)
SinaSyndrome wrote:
"I have this problem where i need to find a way to ask the user to input a number and that number will be set as the size of the array."

This is not possible. An array's length must be constant and known during a declaration context. Some compilers, such as GCC, support non-constant array lengths as an extension, however. To create an array during run-time, you will need to reserve memory from the heap. Here's an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
int main( )
{
    int Value_(0);
    std::cin >> Value_; // Get the length of the array.
    
    int *Memory_(0x0);
    if(Value_ > 0)
        Memory_ = new int[Value_];

    // We're done with the memory.
    delete [] Memory_;
    return(0);
}

See here for further details: http://www.cplusplus.com/doc/tutorial/dynamic/

Wazzak
Last edited on
An array's length must be constant and known during a declaration context. Some compilers, such as GCC, support non-constant array lengths as an extension, however.
Framework is talking about arrays residing on the stack and in static memory (e.g. global arrays are static), not about arrays in general.
Topic archived. No new replies allowed.