Click here to Skip to main content
16,016,345 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
how does sizeof() operator calculates the size of array

What I have tried:

I wrote sizeof(x) to calculate the size of array but I didn't get the expected output.
Posted
Comments
PIEBALDconsult 9-Feb-24 10:36am    
Having to calculate that kind of thing is a code smell. Why did you not store the number you allocated?

sizeof returns the number of bytes used by the parameter: for an array, that the size of each element multiplied by the number of elements.

Try this:
C
#include <stdio.h>

int main()
{
    int arr[10];
    printf("%lu:%lu\n", sizeof(arr), sizeof(arr[0]));

    return 0;
}
And you will get the result "40:4": the array total uses 40 bytes of memory, and each of the 10 elements in the array use 4 bytes.
 
Share this answer
 
Comments
CPallini 9-Feb-24 8:36am    
5.
One small addition: the expression you wrote,
C
sizeof( x ) / sizeof( x[0] )
is used to calculate the number of items in an array. This is the same as what the _countof macro does in VisualStudio C++.

To summarize the three expressions and their result for int x[8] :
sizeof(x)               size in bytes of x             : 32
sizeof(x[0])            size in bytes of one item of x : 4
sizeof(x)/sizeof(x[0])  number of items in x           : 8
 
Share this answer
 
Comments
CPallini 11-Feb-24 4:28am    
5.
You should rather ask yourself why you use a C array instead of a container in C++. You can use the size() method on containers and get the desired size, which you could also adjust at runtime. There are also many other advantages to using the possibilities of C++.
 
Share this answer
 
Comments
CPallini 11-Feb-24 4:28am    
Indeed. 5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900