A pointer is an amazing tool of c language we can do any task easily with the help of pointers. In my previous article, we have read that how to calculate the size of structure without using the sizeof() operator.

In this article, I am calculating the sizeof array without using the sizeof() operator. Calculating the size of an array in c without using the sizeof() operator seems to be difficult but with the help of pointers arithmetic, we can do it easily.

In c language when we increment or decrements the pointer then pointer point the next or previous memory location. The next or previous location depends on the pointer type. If the pfData is a pointer to the float then next location will be 4 bytes ahead of the current location.

In below section, I am writing a program to find the total number of elements in the array (size of the array) without knowing the data type of elements.

### Method 1

Before understanding the above concept I want to remind the relation between array and pointer.

Let’s suppose aiData is an array of integers then &aiData[i] is the pointer to the integer and its value is the address of the ith element. We can also represent the statement in mathematical form.

aiData[i] = *(aiData + i);

*(aiData + i) = aiData[i];

(aiData + i) = &aiData[i];

If the value of i is 0.

(aiData + 0) = &aiData[0];

aiData = &aiData[0];
means that array name is the address of its first element.

Note: But when you put the ampersand(&) before the array name then its type change.It becomes a pointer to the array.

In the short, we can say.

aiData ====> Pointer to the first element of the array .

&aiData ====> Pointer to an array of 6 elements.

*(&aiData+ 1) ====> Dereferencing to *(&aiData + 1) gives the address of first element of second memory block.

*(&aiData+ 1) – aiData ====> Since *(&aiData + 1) points to the address ahead of 6 integers , the difference between two is 6.

### Method 2

Create own sizeof operator using the macro and calculate the total number of elements in the array.

1. #### Holger

Possible, and good learning experience, but dangerous to use in practical programming.

• #### Amlendra

We can use it in practical programming but carefully because it can be dangerous.

2. #### Bengt B

This way of figuring out the size of an array only applies to statically allocated arrays. Pointers are even more interesting when using dynamically allocated memory.

• #### Amlendra

I have written an article to create 1D and 2D array using the pointers(dynamically allocated memory) . http://aticleworld.com/dynamically-allocate-2d-array-c/

To calculate the size of dynamic array,there is no standard or portable way. If you want to know, you will have to keep track of it yourself

Theme by Anders Norén