C++/what could be wrong with my code?
Expert: vijayan - 11/24/2009
QuestionHello ,
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;
}
AnswerYes, 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 ) ;