Bit confused about usage of new to allocate memory dynamically.
e.g. If I need to allocate memory for 100 ints(assuming int is 4 bytes), should I say :
int *ptr = new int[100];
or
int *ptr = new int[100*4]; //assuming int is 4 bytes.
-
Basially new operator allocates memory in bytes or that many bytes of type T used while invoking the new operator?
-
If my class doesn’t have a allocator member function defined, & i need to allocate an array of object of that class type, will the new oeprator find the sizeof(class type) and allocate accordingly or how would it work?
EDIT:
Sorry for clubbing multiple questions, but its related:
will this piece of code work fine if i want to allocate a 2D array of size [100][4] of ints
int *arr = new int [100][4];
thank you.
-AD
The size given to new is the number of items, not the memory size. However, consider using std::vector instead.
For example,
new int[100]allocates at least100 * sizeof(int)bytes (which is 400 when sizeof(int) is 4); any more it allocates will be due to implementation and runtime details which you (except for very rarely) cannot depend on.If you don’t have an operator new or operator new[] in your class (which you usually shouldn’t), then the global versions will be used, and they will use sizeof(your_type) correctly.
Did you try the code in the update?
Multidimensional arrays are actually arrays of arrays; so new returns a pointer to the first item just as it does for single dimensional arrays, which is a pointer to an array:
Again, you’re almost always better off using a container than managing this yourself. That’s vector, et. al., but also containers like boost::array and dedicated “matrix” types for “square” 2-dimensional arrays.