-2
#include<bits/stdc++.h> 
using namespace std;
int main()
{
    int arr[1010];
    memset(arr,1,sizeof(arr));
    cout<<arr[1]<<endl;
    return 0;
}

I am trying to initialise the array with value of 1. I expect my o/p to be 1. But I got some random number(16843009) as o/p of program.I am not understanding what's wrong with the code???

I am getting the expected answer while I am trying to initialise the array with values -1 and 0. Is it possible to initilise the int array using memset with value other than -1 and 0?????

  • Thought about using a `for` loop to initialise it?! – Ed Heal Feb 18 '17 at 07:23
  • 1
    Use memset only if you want to zero-out memory. As mentioned above - it does only work on bytes, thats why you get that value: `0x01010101 == 16843009`. – Shachar Ohana Feb 18 '17 at 07:27
  • Also `using namespace std` is bad See [here](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Ed Heal Feb 18 '17 at 07:27
  • Also, using `#include`is [equally bad](http://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – Bo Persson Feb 18 '17 at 10:38
  • And in C++ you have [`std::fill`](http://en.cppreference.com/w/cpp/algorithm/fill) for filling with values (and not just bytes). – Bo Persson Feb 18 '17 at 10:40

1 Answers1

2

memset sets individual bytes, not entire integers which, typically, span four bytes. If you look at the bits of the number 16843009, it is what you get with four bytes with the value 1. As Ed Heal said, don't complicate things by using memset. Use a loop instead.

Thomas Padron-McCarthy
  • 27,232
  • 8
  • 51
  • 75
  • thanx... but is there any other to initialise instead of using for loops.. the reason i am asking this is .... if i am having 5-d array... i need to write 5 for nested statements in order to initialise the array... can i do it by writing smaller code.. – satyam shekhar Feb 21 '17 at 08:46
  • @satyamshekhar: You _could_ use a single loop, but that will be code that is both obfuscated and brittle, and perhaps not even guaranteed to work correctly. Don't complicate things. If you have a five-dimensional array, use five nested loops. – Thomas Padron-McCarthy Feb 21 '17 at 13:39