Reputation: 19026
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
Upvotes: 2
Views: 1618
Reputation: 14209
The confusion may come because of malloc
which uses data size, not the number of items. To allocate an array of 100 integers, you can do:
int *ptr = (int *)malloc(100 * 4);
or (better, works for all platforms because an int
is not always 4 bytes long):
int *ptr = (int *)malloc(100 * sizeof(int));
instead of:
int *ptr = new int[100];
which, as Fred says, automatically uses the data size to allocate the correct area. Of course malloc
can only be used for built-in types such as int
.
Upvotes: 2
Reputation: 14222
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 least 100 * 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:
typedef int int4[4]; // for clarity
int4 *arr = new int4[100];
// above two lines are identical to:
int (*arr)[4] = new int[100][4];
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.
Upvotes: 4