Dhruv Mullick
Dhruv Mullick

Reputation: 561

Why can't we use std::fill() the same way for 1D and 2D arrays?

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?

Upvotes: 0

Views: 464

Answers (1)

PaulMcKenzie
PaulMcKenzie

Reputation: 35440

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)

Upvotes: 2

Related Questions