Why do arrays have to be statically allocated while pointers may be allocated dynamically?
Why do arrays have to be statically allocated while pointers may be allocated dynamically?
Because pointers aren't really allocated. Pointers are assigned, just like an integer variable would be assigned to a value. Arrays do not have to be statically allocated. Try this:
This little bit of code illustrates dynamic memory allocation with the new operator and pointer assignment.Code:int var = 15; char* arry = new arry[var]; //... later delete arry;
You can create a dynamic array as followsoriginally size was zero but now you have an array that has memory dynamically allocated to itCode:int size=0; int *val; <--pointer cout << "enter arr size"; cin >> size; val = new int[size];
Sophie
simple is always an understatement.....
adding on to this:Originally posted by PorkyChop
Because pointers aren't really allocated. Pointers are assigned, just like an integer variable would be assigned to a value. Arrays do not have to be statically allocated. Try this:
This little bit of code illustrates dynamic memory allocation with the new operator and pointer assignment.Code:int var = 15; char* arry = new arry[var]; //... later delete arry;
you need to delete a dynamically allocated array as follows:
delete []arry;
Another addition: an array in the C sense can still only be allocated statically. The dynamic method makes use of pointers again.
But it doesn't matter if you think in computer terms. It's just memory...
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law
That is the specifications of the C++ programming language.Originally posted by mrcowflops
Why do arrays have to be statically allocated while pointers may be allocated dynamically?
when you declare a pointer, you only reserve space to store one memory address, then if you should allcoate more space to have an array associated with this pointer.
BTW: I don't like this type of titles for threads!
none...