435,414 Members | 2,919 Online
Need help? Post your question and get tips & solutions from a community of 435,414 IT Pros & Developers. It's quick & easy.

# How to calculate the size of int array?

 100+ P: 119 Here's my code for the merge sort algorithm: Expand|Select|Wrap|Line Numbers #include  using namespace std; void merge_(int *, int *, int *); void mergesort(int *); int main(){     int arr[]={7, 2, 1, 3, 6, 8, 10, 9, 5, 4};     mergesort(arr);     cout<<"Array after merge sorting:\n\n";     for(int i=0; i<10; i++){         cout<
4 Replies

 Expert Mod 5K+ P: 9,197 You cannot calculate the size of an array from the name of the array variable. By definition the name of the array variable is a pointer to element 0. From that pointer you cannot calculate the size of the array as there is no array, just a pointer. Read this: https://bytes.com/topic/c/insights/7...rrays-revealed Jun 9 '18 #2

 Expert 100+ P: 2,400 That's why standard library functions such as qsort() and bsearch() have two arguments for array inputs: pointer to start of the array and also the number of elements in the array. Jun 11 '18 #3

 P: 3 In this case you can sizeof. sizeof returns the amount of Bytes the element is using. So the idea is to find the sizeof(array) (in your case which will be 20) and the sizeof(int). The size of an int is 4 Bytes. So now you can use the Math and figure out how to find the array size using this two values. Hope that helps :) Jun 12 '18 #4

 Expert 100+ P: 2,400 @palak10, that will not work in this case. Look at lines 17-18 of the original post to see that @dev7060 tried exactly what you propose. The point of the original post was to find out why it didn't work and to ask what should be done instead. @weaknessforcats provided a succinct explanation why it didn't work and referred the OP to the detailed explanation in Arrays Revealed. I used Standard Library examples to suggest how it could be done. Jun 12 '18 #5