How Do Sizeof(Arr)/Sizeof(Arr[0]) Work

How do sizeof(arr) / sizeof(arr[0]) work?

If you have an array then sizeof(array) returns the number of bytes the array occupies. Since each element can take more than 1 byte of space, you have to divide the result with the size of one element (sizeof(array[0])). This gives you number of elements in the array.

Example:

std::uint32_t array[10];

auto sizeOfInt = sizeof(std::uint32_t); // 4
auto numOfBytes = sizeof(array); // 10*sizeOfInt = 40
auto sizeOfElement = sizeof(array[0]); // sizeOfInt = 4
auto numOfElements = sizeof(array) / sizeof(array[0]); // numOfBytes / sizeOfElement = 40 / 4 = 10

LIVE EXAMPLE

Note that if you pass an array to a function, the above won't work since the array decays to a pointer and sizeof(array) returns the size of the pointer.

std::size_t function(std::uint32_t a[]) // same for void function(std::uint32_t a[10])
{
return sizeof(a); // sizeof(std::uint32_t*)!
}

std::uint32_t array[10];
auto sizeOfArray = function(array); // array decays to a pointer inside function()

LIVE EXAMPLE #2

Is there anything wrong with sizeof(array)/sizeof(array[0])?

Maybe your colleague meant that using this expression with pointers will give an unexpected result. This mistake is made very often by beginners. For example

void f( unsigned char data[] )
{
int data_len = sizeof(data) / sizeof(data[0]);
//...
}

//...

unsigned char data[] = {1,2,3,4,5};
f( data );

So in general case it would be more safely to use a template function instead of the expression. For example

template <class T, size_t N>

inline size_t size( const T ( & )[N] )
{
return N;
}

Take into account that there is template structure std::extent in C++ 11 that can be used to get the size of a dimension.

For example

int a[2][4][6];

std::cout << std::extent<decltype( a )>::value << std::endl;
std::cout << std::extent<decltype( a ), 1>::value << std::endl;
std::cout << std::extent<decltype( a ), 2>::value << std::endl;

Why does my sizeof(arr) / sizeof(arr[0]) = 1?

In your code

polygon[cc].x

is a pointer. by applying sizeof on that pointer, what you get is the size of that pointer itself, not the size of the allocated memory pointed by that pointer.

Remember, arrays are not pointers, so if you apply sizeof on an array, you'll get the size of the whole array.

In your case, sizeof(double *) is equal to sizeof(double), so you get the result as 1.

Why do we get sizeof( &arr ) and sizeof( arr ) / sizeof( int ) different?

Difference is that arr is an array, while &arr is a pointer to the array. Compare to:

#include <iostream>
using namespace std;

int main( )
{
int arr[5] = { 1, 2, 3, 4, 5 } ; // array of 5 integers
int (&ref_arr)[5] = arr; // reference to array of 5 integers
int (*ptr_arr)[5] = &arr; // pointer to array of 5 integers

cout << "array size " << sizeof(arr) << " = " << sizeof(ref_arr) << endl;
cout << "pointer size " << sizeof(&arr) << " = " << sizeof(ptr_arr) << endl;

return 0 ;
}

Possible output (for implementations with 32b integers and 64b pointers):

array size  20 = 20
pointer size 8 = 8

how and why sizeof(a)/sizeof(a[0]) in c is used to calculate the number of elements in an array

According to the C Standard (6.5.3.4 The sizeof and alignof operators)

2 The sizeof operator yields the size (in bytes) of its operand, which
may be an expression or the parenthesized name of a type. The size is
determined from the type of the operand. The result is an integer. If
the type of the operand is a variable length array type, the operand
is evaluated; otherwise, the operand is not evaluated and the result
is an integer constant.

So if you have an array as for example

int a[N];

where N is some integer value then expression

sizeof( a )

yields the number of bytes occupied by the array. As the array has N elements and each element in turn occupies sizeof( int ) bytes then

sizeof( a ) == N * sizeof( int )

or what is the same

sizeof( a ) == N * sizeof( a[0] )

As result you can calculate N the following way

N = sizeof( a ) / sizeof( a[0] )

It is useful if you do not know the exact size of an array for example because its size depends on the number of initializers.

For example

int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
const size_t N = sizeof( a ) / sizeof( *a );

Take into account that sometimes beginners make an error.

Let's assume that you have a function declaring an array as a parameter.

For example

void f( int a[10] );

and the function can be called like

int a[10];

f( a );

Beginners usually write in the body of the function the following expression

void f( int a[10] )
{
size_t n = sizeof( a ) / sizeof( a[0] );
//...
}

However it is a wrong code. The problem is that parameters declared like arrays are adjusted to pointers to the type of the array element. So the function declaration actually looks like

void f( int *a );

and within the function in expression

    size_t n = sizeof( a ) / sizeof( a[0] );

parameter a is pointer. That is it is equivalent to

    size_t n = sizeof( int * ) / sizeof( int );

Depending on the used system pointers occupy either 4 or 8 bytes. So you will get either 2 or 1 if sizeof( int ) is equal to 4.

You will not get the number of elements in the array that was used as the argument.

Pointers do not keep an information about whether they point to a single object or the first object of some array.

In this case you should declare the function with second parameter that specifies the number of elements in the array. For example

void f( int *a, size_t n );

Why is sizeof Function not working here as it is supposed to

Whenever you try to pass an array to any function. The array is implicitly converted to pointer to first element of array. Here in above code as you passed integer array it get converted to
integer pointer which is pointing an array.
That's why you are getting such result. In array cases you need to pass size explicitly in the function. So sizeof is working fine , it is dividing
size of "pointer to array" with the "size of one element".

Reason behind such casting is that "As you must know that arguments are copied into parameters of the function. But in case of arrays.Array can be of variable size they may be larger size. So it's unnecessary to copy such large array.That's why language implement this casting automatically. "

How do I determine the size of my array in C?

Executive summary:

int a[17];
size_t n = sizeof(a)/sizeof(a[0]);

Full answer:

To determine the size of your array in bytes, you can use the sizeof
operator:

int a[17];
size_t n = sizeof(a);

On my computer, ints are 4 bytes long, so n is 68.

To determine the number of elements in the array, we can divide
the total size of the array by the size of the array element.
You could do this with the type, like this:

int a[17];
size_t n = sizeof(a) / sizeof(int);

and get the proper answer (68 / 4 = 17), but if the type of
a changed you would have a nasty bug if you forgot to change
the sizeof(int) as well.

So the preferred divisor is sizeof(a[0]) or the equivalent sizeof(*a), the size of the first element of the array.

int a[17];
size_t n = sizeof(a) / sizeof(a[0]);

Another advantage is that you can now easily parameterize
the array name in a macro and get:

#define NELEMS(x)  (sizeof(x) / sizeof((x)[0]))

int a[17];
size_t n = NELEMS(a);

How to get the length of this array without strlen(), sizeof(arr) / sizeof(arr[0]); does not work, C language

Your code using strlen() may appear the work in this instance but it is not correct.

strlen(arr) makes no semantic sense because arr is not a string. It happens in this case to return 5 because arr has the same address as arr[0], then you kludged it to work for the 6 word output by using the test i <= strlen(arr) in the for loop. The two values strlen(arr) and the number of strings stored in arr are not related.

The expression sizeof(arr) / sizeof(arr[0]) determines the run-time constant number arrays within the array of arrays arr (i.e. 10), not the number of valid strings assigned. It is your code's responsibility to keep track of that either with a sentinel value such as an empty string, or by maintaining a count of strings assigned.

I suggest you change tokenize to return the number of strings (currently it is inexplicably defined to return a char, but in fact only ever rather uselessly returns zero):

int tokenize( char* str, char array[][20] )
{
...

return n ;
}

Then:

int rows = tokenize( find_word_start(str), arr ) ;

for( int i = 0; i < rows; i++ )
{
printf( "token[%d]: %s\n", i, arr[i] ) ;
}

sizeof array elements in C


array elements are treated as pointers

It is not a true. Arrays are NOT pointers. But they decay to pointers to first element when are passed to functions. And sizeof(array) is the number of bytes that whole array occupies.



Related Topics



Leave a reply



Submit