1

I need to dynamically allocate an array of type int with size 12MB. I did it as follows:

unsigned int *memory;
memory = (int *) malloc( 3072 * sizeof(int));

How would I iterate through the array without having to use 3072? Is there a way to get the length of the array? Or should I just do for (int i = 0; i < 3072; i++)?

Thanks

darksky
  • 20,411
  • 61
  • 165
  • 254
  • 2
    possible duplicate of [How to find the sizeof( a pointer pointing to an array )](http://stackoverflow.com/questions/492384/how-to-find-the-sizeof-a-pointer-pointing-to-an-array) –  Nov 29 '11 at 18:48

4 Answers4

4

The is no portable or convenient way to find out how large the allocate chunk is. After malloc is done all that is visible is a pointer to an indeterminate amount of memory (*). You must do the bookkeeping yourself.


(*) Actually malloc and friends do know how large the chunk is but there is no standard way for a client to access this information.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
2

Pointers in C have no inherent length hence there is no way to do this. You must keep the length paired with the pointer throughout it's lifetime.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
0

There is no other way. You should put 3072 in a const int, which would make the code better and more maintainable.

Tore
  • 1
0

With MSVC and MinGW you can use the nonportable _msize function, like

char *c=malloc(1234);
printf("%lu",(unsigned long)_msize(c));
free(c);
user411313
  • 3,930
  • 19
  • 16