You are here:

C++/what could be wrong with my code?

Advertisement


Question
Hello ,

please, when i compile and run this code, it crashes. i am guessing it has to do with with my constructor.. but not sure.. please, could you help me out on why?



#include<iostream>

using namespace std;


class Date{
     unsigned int day, month , year;
     public:
      
         Date(int d, int m, int y);
         
         void Show(){
         cout<<month << "/"<< day << "/"<<year<<"\n";
         }
         };
     
    Date::Date(int d, int m, int y){
         day = d;
         month = m;
         year = y;
         char *str;
         sscanf(str, "%d%*c%d%*c%d", &month, &day,&year);
         }
         
     
     int main(){
        
         Date idata(12,31,99);
         idata.Show();
        return 0;
         }  

Answer
Yes, it has to do with the constructor.

In this code fragment,

       char *str;
       sscanf(str, "%d%*c%d%*c%d", &month, &day,&year);

str is an uninitialized pointer; it does not point to a specific memory location.

You need to allocate memory for an array of char to hold the characters that are the result of scanf.

For example, something like this would be fine:

       char str[128] ; // array of 128 chars
       sscanf( str, "%d %d %d", &month, &day,&year ) ;

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.