-2
我正在尝试编写一种方法将表示日期的C字符串转换为不同的格式。C函数中随机更改值的字符串
/*
Takes in a date of the format MM/DD/YYYY-HR:MN,
and converts it to YYYYDDMMHRMN format.
*/
void convertFormattedDate(char** date){
char* dateHelper = calloc(strlen(*date), sizeof(char));
strcpy(dateHelper, *date);
const char * delims = "/-:";
char* formattedDate = calloc(12+1, sizeof(char)); //leaving space for null terminator
char* token = strtok(dateHelper, delims);
//yes I know this is hacky and terrible
char* month = NULL;
char* day = NULL;
char* year = NULL;
char* hr = NULL;
char* mn = NULL;
int index=0;
while (token!=NULL) {
switch (index) {
case 0:
month = token;
break;
case 1:
day = token;
break;
case 2:
year = token;
break;
case 3:
hr = token;
break;
case 4:
mn = token;
break;
default:
printf("Something weird has happened");
break;
}
token = strtok(NULL, delims);
index++;
}
strcat(formattedDate, year);
strcat(formattedDate, month);
strcat(formattedDate, day);
strcat(formattedDate, hr);
strcat(formattedDate, mn);
*date = formattedDate;
}
当我尝试调用
char* date = "10/24/1994-23:14";
convertFormattedDate(&date);
事情做工精细,直到我开始串联年,月,日等为格式化的日期。我打电话给 strcat(formattedDate,year);
和步骤,通过我的代码,MN的值突然变得
时,只应
有谁知道为什么调用strcat可能会影响其他变量或者我应该怎么做才能防止这种情况发生?
'的sizeof(日期)'将是4或8,你的机器上的指针的大小。 –
Woops,是的。我可能想strlen(*日期)。谢谢! – Kelsey
你为什么改变你的发布代码,是一个错字?这是你的代码,还是不是? –