-6

I'm new to c++, and my program seems to stop working whenever I make a fill call.

void go()
{
    int ints[5];
    cout<<"here";
    fill(ints,ints+sizeof(ints),0);
    cout<<"here2";
}

The odd thing is, it prints both here1 and here2, and then fails. And if i comment out the fill call, the error no longer occurs. I'm sure it's just something that I'm not doing correctly because I'm new, but any help would be greatly appreciated.

TheDarBear
  • 199
  • 1
  • 1
  • 13
  • *it's just something that I'm not doing correctly*: as an example to not show the body of `fill`, if you think the error is there... – skypjack Jan 18 '16 at 23:10
  • Take a look at some awesome C++ books, they will help you to avoid such confusions in the future: [The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – Ivan Aksamentov - Drop Jan 18 '16 at 23:10
  • @skypjack fill is a c++ method, not mine – TheDarBear Jan 18 '16 at 23:14
  • Possible duplicate of [How do I find the length of an array?](http://stackoverflow.com/questions/4108313/how-do-i-find-the-length-of-an-array) – Captain Obvlious Jan 18 '16 at 23:16
  • 1
    @user2659185 My fault, I guessed it was something you wrote for exercise. I'm sorry. – skypjack Jan 18 '16 at 23:19

1 Answers1

4

sizeof returns the size of the given type in number of chars, not the number of elements in the array (i.e. you have the wrong units). Therefore, ints+sizeof(ints) is incorrect, it should be ints + 5.

Daniel
  • 8,179
  • 6
  • 31
  • 56
  • Thanks! works perfectly. for arrays for which I didn't know the size, would it also be sufficient to say fill(ints,ints+sizeof(ints)/sizeof(int))? – TheDarBear Jan 18 '16 at 23:16
  • 2
    @user2659185 Better to use [`std::array`](http://en.cppreference.com/w/cpp/container/array) which has `begin` and `end` member methods (and a `size` member method). – Daniel Jan 18 '16 at 23:19
  • 1
    Well it does give you the size of the array. The part that is incorrect is that the size of the array is `sizeof(element_type) * array_size`. When dealing with arrays and `sizeof()` the correct approach is `sizeof(array_name) / sizeof(array_name[0])` – NathanOliver Jan 19 '16 at 00:18
  • 1
    @Daniel: C++11 also added [`std::begin`](http://en.cppreference.com/w/cpp/iterator/begin) and [`std::end`](http://en.cppreference.com/w/cpp/iterator/end) free functions that work with arrays too. – Blastfurnace Jan 19 '16 at 00:37
  • @NathanOliver Well you have used "size" to mean two things here, but you're right, edited to make it clearer. – Daniel Jan 19 '16 at 10:45