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.

Recommended Answers

All 6 Replies

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).

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.

See my edits in the last post.

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. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.