title: C++ dynamic memory allocation with arrays in a structure
body: <p>There have been similar questions to this but they are all in C, rather than C++, so I have asked a new question.</p>
  
  <p>I have been following a <a href="http://www.cplusplus.com/doc/tutorial/structures/" rel="nofollow">C++ tutorial</a> and after completing the dynamic memory, pointers and structure sections I tried to put them together in an example program.</p>
  
  <p>Essentially, I am trying to have a dynamically allocated array of a structure (the program inputs "produce" :P and displays the result).</p>
  
  <p>The compiler errors: <code>'base operand of '-&gt;' has non-pointer type 'produce'</code> for the code <code>fruit[i]-&gt;item;</code></p>
  
  <p>Sorry if the code is a bit long winded (I didn't want to leave out sections in case they were the problem, even if this results in the question being 'too localised'):</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;string&gt;
  #include &lt;new&gt;
  
  using namespace std;
  
  struct produce {
      int price;
      string item;
  };
  
  int main(void) {
      int num;
      int i;
  
      //Get int for size of array
      cout &lt;&lt; "Enter the number of fruit to input: ";
      cin &gt;&gt; num;
      cout &lt;&lt; endl;
  
      //Create a dynamically allocated array (size num) from the produce structure
      produce *fruit = new (nothrow) produce[num];
      if (fruit == 0) {
          cout &lt;&lt; "Error assigning memory.";
      }
      else {
          //For 'num', input items
          for (i = 0; i &lt; num; i++) {
              cout &lt;&lt; "Enter produce name: ";
              //Compiler error: 'base operand of '-&gt;' has non-pointer type 'produce'
              cin &gt;&gt; fruit[i]-&gt;item;
              cout &lt;&lt; endl;
  
              cout &lt;&lt; "Enter produce price: ";
              cin &gt;&gt; fruit[i]-&gt;price;
              cout &lt;&lt; endl;
  
              cout &lt;&lt; endl;
          }
          //Display result
          for (i = 0; i &lt; num; i++) {
              cout &lt;&lt; "Item: " &lt;&lt; fruit[i]-&gt;item &lt;&lt; endl;
              cout &lt;&lt; "Cost: " &lt;&lt; fruit[i]-&gt;price &lt;&lt; endl;
              cout &lt;&lt; endl;
          }
          //Delete fruit to free memory
          delete[] fruit;    
      }
  
      return 0;
  }
  </code></pre>