Christopher Zhou
Christopher Zhou

Reputation: 181

2D double array not being filled up with value

In my program, I am trying to fill a 2-dimensional array of doubles with the constant value of DBL_MAX. However, when I debug my code, I find that the array is filled with the value of 0, not DBL_MAX, even after I step past the array-filling code. Is there something I am doing wrong?

Here is my code for filling the double 2d array

double array[150][150];
memset(array, DBL_MAX, sizeof(array));

Upvotes: 1

Views: 87

Answers (2)

user4442671
user4442671

Reputation:

memset() is simply the wrong tool for the job here.

it's declared as:

void* memset( void* dest, int ch, std::size_t count );

Where ch will be assigned to each byte of data. If you test what DBL_MAX is, when casted to int, you can confirm why you are getting zeros:

int x = DBL_MAX;
std::cout << x << "\n"; // prints 0

You could mess with casting and std::fill, but that would look pretty bad in my opinion, I think you are better off using a simple double-loop and let the compiler take care of optimizing it for you:

for(auto& l : array) {
  for (auto& c : l) {
    c = DBL_MAX;
  }
}

Edit: Since you've tagged this as C++11, a general comment: unless you are interacting with APIs and interfaces that work directly on memory, you really should not be thinking in terms of "memory" when writing modern C++ code. Even when dealing with the core data types, it's almost always better to treat them as objects. If you are using any of the old mem... interfaces, odds are you are tackling your problem from the wrong angle.

Upvotes: 2

M.M
M.M

Reputation: 141554

memset sets each byte to the value provided. However you actually want to set each double.

You can use:

double array[150][150];
std::fill_n(&array[0][0], 150 * 150, DBL_MAX);   // #include <algorithm>

It is also possible to use template metaprogramming to generate code basically equivalent to double array[150][150] = { DBL_MAX, DBL_MAX, DBL_MAX, .... , see this thread for ideas.

Upvotes: 1

Related Questions