Welcome to Dream.In.Code
Become a C++ Expert!

Join 149,728 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,332 people online right now. Registration is fast and FREE... Join Now!




Dynamic array of structures problem

 
Reply to this topicStart new topic

Dynamic array of structures problem, Program compiles ok but when I run it there is a problem

codemax88
7 Feb, 2007 - 06:29 PM
Post #1

New D.I.C Head
*

Joined: 7 Feb, 2007
Posts: 33


My Contributions
When I run this simple program window xp warning interrupts my program asking me to end the program and to send the offending content to them. I'm using Dev-c++ bloodshed compiler. Is my dynamic memory allocation causing the problem or just lousy coding?
//
CODE

#include <iostream>
#include <string>
using namespace std;
struct  Car
{
  std::string make;
  int year;};
  int size;
int main(int argc, char **argv)
{
  
   Car *amount;
      amount = new Car [size];  
    
  cout<< "How many cars do you want to catalog?" <<endl;
  cin >> size;

  cout<< endl;
  cout << "Please enter the make of car"<<endl;
  cin >> amount ->make;
  cout << endl;
  cout << "Please enter the year made:";
  cin>> amount ->year;
  cout << endl;
  cout << "Here is your collection:";
  cout << amount -> year << " "<<  amount -> make <<endl;
    
    
    
    
        
    
  system ("pause");
  delete []amount;  
     return 0;
     }

User is offlineProfile CardPM
+Quote Post

ByteWyse
RE: Dynamic Array Of Structures Problem
7 Feb, 2007 - 07:07 PM
Post #2

New D.I.C Head
*

Joined: 2 Jan, 2007
Posts: 41


My Contributions
CODE

   Car *amount;
   amount = new Car [size];  


Where is 'size' defined? Is it initialized before its first use?



User is offlineProfile CardPM
+Quote Post

AmitTheInfinity
RE: Dynamic Array Of Structures Problem
7 Feb, 2007 - 08:53 PM
Post #3

C Surfing ∞
Group Icon

Joined: 25 Jan, 2007
Posts: 1,153



Thanked: 44 times
Dream Kudos: 125
My Contributions
QUOTE(codemax88 @ 8 Feb, 2007 - 07:59 AM) *

CODE

  
   Car *amount;
      amount = new Car [size];  
    
  cout<< "How many cars do you want to catalog?" <<endl;
  cin >> size;




You are using size even before it is initialised, so it might have some garbage value stored in it which makes problem while creating array and assigning memory to it. This compiles properly but generates run time errors. so try to create array after you get value for size.

CODE

  
  Car *amount;
    
  cout<< "How many cars do you want to catalog?" <<endl;
  cin >> size;

  amount = new Car [size];  



I hope this will work for you.
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 1/8/09 05:09AM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month