Getting number of elements in an array

Started by
8 comments, last by wyrzy 18 years, 11 months ago
Is it possible to get the number of elements allocated by new[]? As in... assume I did the following... int* x = new int[100]; /* A lot of code */ cout << *number of elements allocated by x* << endl; delete[] x; So that the output would be 100. Surely this number must be stored somewhere since delete[] manages to delete 100 ints safely, so the question is how can I access this number so I know how many elements x points to? Thanks.
Advertisement
why not do

#define MY_ARRAY_SIZE 100

...

int *x = new int [MY_ARRAY_SIZE];

/*
A lot of code
*/

cout << MY_ARRAY_SIZE << endl;
delete[] x;
This number is indeed stored in your running process memory, however you do not have access to it, as the implementation is compiler-dependent. If you'll output the assembly listing of your program, you could see how your compiler does it, but it uses local, transparent variables that are not available to you.

If the size matters, why don't you just keep it?
Dubito, Cogito ergo sum.
Only somewhat snarky:

std::vector<int>    x;/*tons of code*/std::cout << "Eliminating " << x.size() << " ints." << std::endl;x.clear();


Arrays suck in so many more ways than this. The language provides nicer options, if that's what you need.

Otherwise DadleFish is correct.
Can't you just use sizeof?
actually arrays are beautiful in a lot of ways, for instance if you will be deleting and adding entries into and out of the memory, then an array is a lot lot faster then a vector, or other alternatives. the best option is to use the sizeof function

int array = new int[100]; //( you can put any number here )
cout << "num elements " << sizeof(array)/sizeof(int);
delete [] array;
Quote:Original post by smr
Can't you just use sizeof?


No. When you dynamically allocate an array, the variable is simply of a pointer type, so sizeof will return only the size of a pointer—usually 4 on 32-bit platforms, 8 on 64-bit platforms, et cetera.
Quote:Original post by DarkMerchant
actually arrays are beautiful in a lot of ways, for instance if you will be deleting and adding entries into and out of the memory, then an array is a lot lot faster then a vector, or other alternatives. the best option is to use the sizeof function

int array = new int[100]; //( you can put any number here )
cout << "num elements " << sizeof(array)/sizeof(int);
delete [] array;

The output from that code (when 'array' is a pointer to an int) will be 1 (assuming 32-bit pointer and 32-bit int).
sizeof([insert any type of pointer here])==4, provided you are a 32-bit system where pointers are 32-bits long.

Also, if you're using VC++, you can find the size of a block of memory in the heap using _msize( void *array );

Here's an updated example:
int *array = (int *)malloc(100*sizeof(int)); //( you can put any number here )
cout << "num elements " << _msize(array)/sizeof(int);
free(array);

I tested that with default settings in VC++ in Release mode and it works fine for me. I was having trouble with Debug mode, though. Remeber, its VC-specific so it won't work with say DevC++.[EDIT: Works fine with MinGW as well - compiler for DevC++]

[EDIT]Forgot to mention that _msize() doesn't work with new and delete (at least to my knowledge). If you really don't like malloc() free(), you could #define some MACROS to emulate the appearance, but that would just be more trouble than its worth, IMO.[/EDIT]

[Edited by - wyrzy on May 21, 2005 1:19:31 PM]
You cannot use sizeof for the reasons described by others. The only place this would work is on static arrays, e.g. -

int arr[100];
int size = sizeof(arr)/sizeof(int);

This would make size=100.

And something else to add on top of my former answer - when you ask the system to allocate X bytes, the system might allocate Y bytes, when Y>=X. This means that even if you've had a way to get Y, it might not be what you asked for in the beginning. In order to let the system have this freedom, you cannot know what you've asked for.

I'd use STL like was suggested, or have a constant saving my array size.
Dubito, Cogito ergo sum.
Quote:This number is indeed stored in your running process memory, however you do not have access to it

I'm not *exactly* sure, but I think that _msize() does get you the size when the process is running if you used malloc() (does not apply to new).

Also, I just tried it with MinGW, and _msize() does work on it, so if you're using DevC++ you should be find too. I'm still pretty sure that _msize() is not standard, but then again itoa [converts an integer to a char * string] is not standard either and I see people using it all the time.

I googled a little, and some people said that malloc() can allocated more bytes than requested, so I made a little test app to see, but malloc always seemed to allocate the requested size. I think it should be pretty safe to use.

While it doesn't really answer the new[] question, using malloc() and free() can sometimes come in handy if you need to re-size that array ( using realloc() ) but you don't want to create a new one, copy the contents in the the new, and delete the old one. Using realloc() will allow you to expand the size of a dynamically allocated block of memory while preserving the original contents.

Here's the source to my test program:
#include <malloc.h>#include <stdlib.h>#include <stdio.h>int main(){  for(int i=0; i<100000; i++)  {    int rand_int = 1 + rand()%100000;    printf("Allocating %d-Bytes\n", rand_int);    int *array = (int*)malloc(rand_int);    printf("  --  Bytes On Heap %d\n",_msize(array));    if(_msize(array)!=rand_int)    {      printf("size requested and size reported do not match");      exit(1);    }    free(array);  }}

This topic is closed to new replies.

Advertisement