Thread: why does my code crash

  1. #1
    Registered User
    Join Date
    Nov 2002
    Posts
    319

    why does my code crash

    Code:
    #include <iostream>
    using namespace std;
    
    struct Measurements
    {
    int lenght;
    int width;
    int height;
    //need a constructor
    
    Measurements()
    {
    lenght = 1;
    width = 2;
    height = 3;
    }
    
    }; 
    
    //its not much code , but why would this crash
    int main()
    {
    Measurements *Measure;    
    cout<<Measure->height<<endl;
    return 0;
    }

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Measure is an uninitialized pointer.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Bond sunnypalsingh's Avatar
    Join Date
    Oct 2005
    Posts
    162
    Do this
    Code:
    Measurements *Measure=new Measurements;

  4. #4
    Registered User
    Join Date
    Jan 2006
    Posts
    19
    Don't you need to create an instance of the structure in main, or is that just classes?

  5. #5
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    Messages is a pointer -- and all pointers must be initialized before they can be used. In c++, structures and classes are nearly identical.

  6. #6
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    In this simple example, there is no reason to use a pointer at all. Declare Measure as a local variable, and access the height as Measure.height.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Proposal: Code colouring
    By Perspective in forum A Brief History of Cprogramming.com
    Replies: 28
    Last Post: 05-14-2007, 07:23 AM
  2. Explain this C code in english
    By soadlink in forum C Programming
    Replies: 16
    Last Post: 08-31-2006, 12:48 AM
  3. Updated sound engine code
    By VirtualAce in forum Game Programming
    Replies: 8
    Last Post: 11-18-2004, 12:38 PM
  4. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM
  5. Replies: 0
    Last Post: 02-21-2002, 06:05 PM