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

Tim Cooper
  • 151,519
  • 37
  • 317
  • 271
darksky
  • 19,342
  • 60
  • 161
  • 247
  • 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) – Tim Cooper 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
  • 172,020
  • 25
  • 347
  • 381
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
  • 703,665
  • 143
  • 1,211
  • 1,438
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,800
  • 17
  • 16