0

Whats the problem with sizeof()??

When i define an array and want to find the length of that by sizeof() , it doesn't work properly , int a[3]={1,3,4}; int b = sizeof(a); cout<<b; The output must be 3 , while it shows 12 . What's the problem ?? Although I do know that there's an alternative I mean *(&a+1)-a , which works so well.

9th Dec 2020, 11:49 AM
Ali_combination
Ali_combination - avatar
8 ответов
+ 5
A int in this case is 4 bytes and 4*3=12.
9th Dec 2020, 11:51 AM
Aaron Eberhardt
Aaron Eberhardt - avatar
+ 5
Ali_combination the array has 3 ints. The size of 1 int is 4 bytes and therefore the size of array of 3 ints is 4*3 = 12 bytes
9th Dec 2020, 12:07 PM
XXX
XXX - avatar
+ 4
to get the size of the array , you should be doing sizeof(a)/sizeof(int)
9th Dec 2020, 12:14 PM
Hima
Hima - avatar
+ 2
You are all right ! 👍 Thank you so much gentlemen.
9th Dec 2020, 12:17 PM
Ali_combination
Ali_combination - avatar
+ 1
Aaron Eberhardt You are right , thanks a lot. I apologize for downvoting your comment.
9th Dec 2020, 12:23 PM
Ali_combination
Ali_combination - avatar
+ 1
Ali_combination no need to apologize :)
9th Dec 2020, 1:25 PM
Aaron Eberhardt
Aaron Eberhardt - avatar
- 3
Nope , take a look at this a=[3]={1,2,3} int b = sizeof(a); Cout<<b; The outputs is 12.
9th Dec 2020, 11:54 AM
Ali_combination
Ali_combination - avatar