Find size of an array using pointer hack in C/C++

BM Monjur Morshed
2 min readMay 11, 2020

Greetings!

We can find the size of an array in C/C++ using ‘sizeof’ operator. Today we’ll learn about a small pointer hack, so that we will be able to find the size of an array without using ‘sizeof’ operator. So let’s proceed.

Code:

#include <bits/stdc++.h>
using namespace std;

int main()
{
int ara[] = {1, 1, 2, 3, 5, 8, 13, 21};
int size = *(&ara + 1) - ara;
cout << “This array has “ << size << “ elements\n”;
return 0;
}

Output:

This array has 8 elements

So we got the size of the array.

Okay don’t start abusing me, I’m going to explain what I did. So in the main function, we declared an array and then we assigned values to that. In the next line we used pointer arithmetic to do the actual job.

We know that the name of array holds the address for the first element. Like here ara holds the address of the first element of this array. But what does &ara holds? Let’s print the values of them.

Output:

Value of ara: 0x61feec
Value of &ara: 0x61feec

So both output are same. Then how can we find the size of array from this? Okay now let’s print the value of (ara+1) and (&ara+1) and then see what happens.

Output:

Value of (ara+1): 0x61fef0
Value of (&ara+1): 0x61ff0c

So we didn’t get the same output now. Why? Because the name of an array (ara in this case) holds the address of the first element (address of ara[0]) and when we increase the value by 1, it now holds the address of the next element (address of ara[1]). But &ara holds the address of whole array. what does it mean? It means if we increase the value of &ara, it will now point to the next address of the last element.

To make you more clear, let’s take our code as an example. When we printed the value of (&ara+1), it is pointing to an address of 8 integers ahead. If we calculate,

(&ara+1) = 0x61ff0c = (0x61feec + 8) (According to pointer arithmetic)

(&ara+1) - ara = ((0x61feec + 8) — 0x61feec)= 8

So we understand how it works right? Then why do we have to use ‘*’ before (&ara+1) ? Because &ara holds the address of whole array. So we use ‘*’ to convert it into a integer pointer and then subtract the address of first element from it.

That’s all, hope you understand the topic.

--

--