1

I am wondering if there is a way to clear memory/data that is inputted in a structured array?

struct order{
int qtyData;
double priceOrder;
string nameOrder;
}food[20];
//Clear the Arrays <-- Error!!!
fill_n(food[20].qtyData, 20, 0);
fill_n(food[20].priceOrder, 20, 0.00);
fill_n(food[20].nameOrder, 20, "");

2 Answers2

0

You have a couple of problems.

First, arrays are 0 based. That means that the first element is 0, and the last one (in your case) is 19. There is no 20. Consequently, referring to food[20] is undefined behavior, which allows your program to do literally anything, although the most likely is probably your program crashing.

The second problem with your code is that std::fill_n() looks for the first object you want filled, not the last. That means, you want food[0], not food[20]:

fill_n(food[0].qtyData, 20, 0);
fill_n(food[0].priceOrder, 20, 0.00);
fill_n(food[0].nameOrder, 20, "");

Something like that should work, although--full disclosure--it is untested. But it should be in the general ballpark of what you need.

The only other thing that I see that could be a problem is by calling something like food[0].qtyData, std::fill_n() may not work like you would think it would, since qtyData is an int. I'm not familiar enough with std::fill_n(), but I think it might only clear the next 20 ints, not the next 20 qtyDatas. You may need the full struct like this instead:

fill_n(food[0], 20, 0);

Although, again, this is still untested.

  • Can you explain which value will be, after `fill_n` usage at `food[15].qtyData`? And at `food[15].nameOrder`? – Ripi2 Jul 25 '19 at 23:34
  • I'm afraid not. I'm not too familiar with `fill_n()`. I can merely make an educated guess, which is that it'd treat the memory stored at `food` as an array of `int`s, which would basically bleed into the memory stored in other parts of the struct. But I'm not 100% positive. –  Jul 26 '19 at 00:49
0

Not sure that I understand you question correctly, but you can assign a complete struct at once, like so:

    std::fill_n(std::begin(food), 20, order{0, 0.0, ""});

This overrides 20 entries in the array food with order{0, 0.0, ""}, starting from the beginning.

If you use std::fill instead, you don't have to repeat the size like this:

    std::fill(std::begin(food), std::end(food), order{0, 0.0, ""});

which fills all elements, whatever the size of the array.

fweik
  • 441
  • 3
  • 5