0

I am looking for a way to get the length of an array for the pointer address. An example:

int *a = (int*)malloc(sizeof(int)*2);// will be an array. 
*(a+0) = 1; // values of the array
*(a+1) = 2;

Is there a way to detect how much memory is allocated by this pointer? We suggest that there are no empty elements in this array. If I know how much memory is allocated, I should be able to get the size of an array (deviding by sizeof(int));

NumberTheory
  • 1
  • 1
  • 5
  • 1
    A more usual way to write `*(a+1)` is `a[1]` – pmg Feb 08 '15 at 09:37
  • 3
    No. `a` is a pointer. The only portable way to know the size of the memory block it points to is to store that size. – juanchopanza Feb 08 '15 at 09:38
  • I know. But this way of adressing is helpful to understand what an array is. Thank you. Can you also tell me why it is used size_t as a datatype for this memory blocks (for its size)? – NumberTheory Feb 08 '15 at 09:38
  • @NumberTheory An array is just elements laid out contiguously in memory. There's nothing special about that. – Emil Laine Feb 08 '15 at 09:39
  • The "will be an array" comment is sort of misleading, really, it's just 2*sizeof(int) bytes of memory. You can just as well use it for a struct with int x,y as an array. – perh Feb 08 '15 at 09:40
  • 1
    size_t is used because it, unlike int, is guaranteed to be big enough for any memory block that can be allocated. There is nothing special about it, it's just an unsigned int of a suitable size. – perh Feb 08 '15 at 09:41
  • Thank you. That helped so much. Can you add it as a seperate answer so that I can mark it as solved? – NumberTheory Feb 08 '15 at 09:42
  • 2
    The answer to "*What is size_t...*" is here: http://stackoverflow.com/q/2550774/694576 Please do some minimal research before posing questions. – alk Feb 08 '15 at 09:48

0 Answers0