You are here:

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


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?


using namespace std;

class Date{
     unsigned int day, month , year;
         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);
        return 0;

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 ) ;


All Answers

Answers by Expert:

Ask Experts




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.


about 15 years or so

post graduate engineer

©2016 All rights reserved.