1

Here is my code, I would need to fill in every element in the 2d array with the maximum size ( INT_MAX), however, my code was unable to work properly?

#include <iostream>
#include <string.h>
#include <limits.h>
using namespace std;
int main(){
    int arr[10][10];
    memset(arr,INT_MAX, sizeof (arr));
    cout << arr[0][3];
//output = -1 instead of 2147483647


}

How do I modify my code such that I will be able to fill in an array with the max values?

pzaenger
  • 11,381
  • 3
  • 45
  • 46
James
  • 27
  • 5
  • 3
    `memset` writes bytes, `INT_MAX` is not a byte. I would just write a for loop. – john Feb 11 '21 at 15:25
  • But your code would work if you changed `int arr[10][10];` to `unsigned arr[10][10];` and changed `INT_MAX` to `UCHAR_MAX`. – john Feb 11 '21 at 15:26
  • @john While technically true (for most reasonable architectures) I'm sure the reasons why are beyond James' current understanding and it likely would confuse them more than that it helps. – orlp Feb 11 '21 at 15:28
  • 1
    See some ideas [here](https://stackoverflow.com/q/3948290/509868). – anatolyg Feb 11 '21 at 15:37
  • https://stackoverflow.com/questions/32693135/initializing-entire-array-with-memset – Pierre Baret Feb 11 '21 at 15:47

1 Answers1

3

C++ Standard Library has a function fill_n to fill arrays with n values.

#include <algorithm>
...
std::fill_n(&arr[0][0], 100, INT_MAX);

The number of values may be brittle here - if you change the size of the array in future, you have to remember to change the hard-coded 100 to a new correct value.

It's good enough for a quick hack. If you need something with long-term value, use the idea in this answer to a similar question.

anatolyg
  • 26,506
  • 9
  • 60
  • 134