0

I have the following code in C:

int array[5] = {0,1,2,3,4}; 

int * p = &array[0];

how to use the pointer p to get the size of this array p point to?

ratzip
  • 113
  • 2
  • 11

5 Answers5

7

Sorry, this is actually impossible. The size of an array is not saved anywhere. You'll have to do it yourself.

Yves Dubois
  • 933
  • 4
  • 7
2

It can't be done just from a pointer. The pointer is literally the address in memory of the first element of the array. The array size is not automatically associated with this pointer. You must keep track of the size yourself.


One workaround you can use is to reserve a special value for your array elements, say -1. If you can arrange for your last element to always have this value, then you can always find the end of the array by searching through it for that value. This is why strings have a null terminator, so strlen() and family can find the end of the string.

Digital Trauma
  • 15,475
  • 3
  • 51
  • 83
1

The short answer: In C, an array size cannot be retrieved from a pointer. The size must be passed separately.

The slightly-less-short answer: In C, a pointer is just an address to a spot in memory. The pointer does not even guarantee that there is a valid array or variable here; it is just a descriptor of a memory location.

In fact, in C, the concept of an array "size" is somewhat loose. A certain amount of consecutive memory can be allocated, but there is no checking as to if a pointer leaves this memory.

For example:

int a[] = {1, 2, 3};
int b = a[7];

will compile properly. C does not have any bounds checking!

Glenn
  • 1,059
  • 6
  • 14
  • 1
    No checking doesn't mean the concept of size is loose. It just means overflowing buffers is not strictly and consistently punished. That's what UB is for. – Deduplicator Mar 27 '14 at 15:29
0

you can not know the size of array using pointer to it. you cant determine since there is no way to know the end of array or to know that we reached the last element of array.

LearningC
  • 3,182
  • 1
  • 12
  • 19
0

So, after reading 5 previous answers, here a better one:

a) You cannot get the element count of an array using a pointer. Common workaround are:

  • Using a sentinel value (see C-String aka asciiz)
  • Passing the length separately. (see counted strings using mem*())
  • Actually using a struct, resp. reserving element 0 (or -1) for a lenght value. (also see counted strings).
  • Just allocate a whopping big amount of memory you know will suffice and not bother with the actual length at all. Getting this wrong is fun and easy to do.

b) You can get the element count of an array using the array name:

struct foo[my_expr];
ìnt count = sizeof array / sizeof *array;
Deduplicator
  • 44,692
  • 7
  • 66
  • 118