0

I have seen that if we have a 1D array int A[10], then to fill it with an arbitrary value, say 0, we use std::fill(A, A+10, 0)

For a 2D array B[10][10], we fill it with 0 as: std::fill(&B[0][0], &B[0][0] + sizeof(B), 0

However, I can't understand why we can not fill the 1D array A as: std::fill(&A[0], &A[0] + sizeof(A), 0

Can someone explain this?

1
  • 1
    sizeof(A) returns the number of bytes, not the number of items. The std::fill function wants the number of items. Commented Feb 1, 2015 at 19:39

1 Answer 1

2

The sizeof(T) returns the number of bytes of type T. It does not return the number of items if T is an array type (if you discount T[0] being a char type).

For the number of items in an array, it would be sizeof(T) / sizeof(T[0]), so the fill function would be this:

std::fill(&A[0], &A[0] + sizeof(A)/sizeof(A[0]), 0) 
Sign up to request clarification or add additional context in comments.

5 Comments

What happens in case of the 2D array?
You have the same error in your question for the 2D array. The same solution applies there too.
According to this answer (stackoverflow.com/a/3948314/2647199), the command for filling the 2D array should work fine.
Look at my answer. See where I say "discounting T being a char type"? The answer you linked to only works if the type is char. If the sizeof(T[0]) > 1 then you must do as my answer states. My answer even works if the type is char, so you don't lose anything if you use it.
I edited my answer to emphasize the point that if T[0] is not a char type, the number of items in an array can be derived by dividing the array size (in bytes) by the size of each element (in bytes).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.