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?

Dhruv Mullick
  • 551
  • 9
  • 25
  • 1
    `sizeof(A)` returns the number of bytes, not the number of items. The `std::fill` function wants the number of items. – PaulMcKenzie Feb 01 '15 at 19:39

1 Answers1

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)
PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45
  • What happens in case of the 2D array? – Dhruv Mullick Feb 01 '15 at 19:44
  • You have the same error in your question for the 2D array. The same solution applies there too. – PaulMcKenzie Feb 01 '15 at 19:46
  • According to this answer (http://stackoverflow.com/a/3948314/2647199), the command for filling the 2D array should work fine. – Dhruv Mullick Feb 01 '15 at 19:48
  • 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. – PaulMcKenzie Feb 01 '15 at 19:51
  • 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). – PaulMcKenzie Feb 01 '15 at 19:59