Question:

Help on initializing an array with all elements empty using a for loop C++?

by  |  earlier

0 LIKES UnLike

Here is a little snippet of my code

dispensers is of data type struct

struct dispensers

{

int dispenser;

int cost;

int quantity;

string product;

};

dispensers initialSetup[5];

for (k=0; k<5; k++)

{

initialSetup[k] = 0;

}

What am I doing wrong?

 Tags:

   Report

4 ANSWERS


  1. see if this helps

    for(int k=0; k&lt;5; k++)


  2. If you want to, you could also turn it into a class instead of a struct, and initialize all the members in the constructor.

    class dispensers

    {

    public:

    dispensers();

    int dispenser;

    int cost;

    int quantity;

    string product;

    };

    dispensers::dispensers()

    : this-&gt;dispenser(0), cost(0), quantity(0), product(&quot;&quot;) //or whatever

    {}

    then all you need to do is the

    dispensers initialSetup[5];

  3. you&#039;re using a managed type in a struct, that&#039;s a little bit dodgy, check your compiler error and post it here if you can.

    other than that, you have an array of structs, you need to actually set a member rather than just trying to edit the struct itself;

    initialSetup[k].cost = 0; //(for example)

  4. lol looking at this code reminds me of my foolish mistakes I used to do when I was learning C. :D

    Think again what is &quot;struct&quot; type?

    Any variable declared with &quot;struct&quot; type becomes a &lt;b&gt;complex variable type&lt;/b&gt; consisting of set of simple variables otherwise called structure. Remember COMPLEX variable type!!! This is your problem. You should initialize simple variables inside the structure not the structure itself.

    More correct version:

    for (k=0; k&lt;5; k++)

    {

    initialSetup[k].dispenser = 0;

    initialSetup[k].cost = 0;

    &lt;* ... and initialize rest of the variables also*&gt;

    }

    But you also have another problem with your code: you need to ALLOCATE MEMORY for complex variable type, which you didnt do in your source code.

    I will not tell you how, try to figure it by yourself, it is just simple one line statement.

Question Stats

Latest activity: earlier.
This question has 4 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.