Hey, I'm new to C++ (1 week, used to do Python), and it's very enjoyable, but I have an issue. In the following code:

int sizeofarray;
cout << "Type size of array: ";
cin >> sizeofarray;
int myarray[sizeofarray];
...........more code

That isn't the code, but that is the EXACT situation and context my problem is. I have tried using the dynamic pointer method (if that is even how you would handle this situation), but it didn't work (even though I probably misdid it, but I couldn't find a very clear explanation of how to do it anyway). Any help would GREATLY be appreciated! :)

-AP

EDIT:

I'm sorry, I forgot to even post my problem, even though it's obviously evident to you l33t hacker people. During the building process, the compiler requirees 'myarray' to have a defined size, even though it can only be inputted at runtime.

Edited 5 Years Ago by AutoPython: n/a

Yes, you would want a dynamic allocation. In C++, a fixed-size array's size must be a constant known known at compile time.

You need int * myarray = new int[sizeofarray]; Since the array is dynamically allocated with new, you need to delete it to free up the memory, delete [] myarray;

I hate to be acting like I'm lazy, but could you give me a code sample with the dynamic allocation? I haven't seen a code snippet and it would REALLY help to see an example.

-A.P.

Substitute the line that I wrote into your code sample on line 4. If you do that, does it still give you an error? There's not that much more to it.

Not trying to be mean here, I guess I don't know what else you need to see.

BTW, if I don't mention it, someone else will, but some compilers do allow you to declare arrays with a variable size like you did, but it's an extension to the language and therefore non-standard (so probably not recommended).

Edited 5 Years Ago by jonsca: n/a

Oh, I'm so stupid. I did that, but I when I transposed the code back to the original, I mixed up a variable or two. Much thanks for solving the problem! Couldn't find a straight answer anywhere.

-A.P.

Oh, I'm so stupid. I did that, but I when I transposed the code back to the original, I mixed up a variable or two. Much thanks for solving the problem! Couldn't find a straight answer anywhere.

-A.P.

Glad to help. :)

This question has already been answered. Start a new discussion instead.