What I want to do is to get parameter from cmd line arguments, like that: 12/24/2000, and store them into int mm, int d, int yyyy; It could print out correctly, but shows me wrong value, when I pass them into a function.
int main(int argc, char* argv[]) {
int x, y, d, mm, yyyy;
char* a = (char*)malloc(sizeof(char));
a = argv[1];
x = getDateKey(9, 27, 2022);
printf("%d\n", x);
sscanf(argv[1], "%d/%d/%d", &d, &mm, &yyyy);
y = getDateKey(d, mm, yyyy);
printf("%d\n", y);
return 0;
}
What print is when I execute (myprogram 9/27/2022):
270 (correct)
-118647133
EDIT code of getDateKey:
#include <stdio.h>
#include <stdlib.h>
#include "lab4.h"
int getDateKey(int month, int day, int year) {
int i, key, check = 0;
if(isLeap(year)){
check = 1;
}
for(i = 1; i < month; i ) {
if(i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10 || i == 12) {
key = 31;
} else if(i == 2) {
if(check) {
key = 29;
} else {
key = 28;
}
} else {
key = 30;
}
}
return key = day;
}
CodePudding user response:
A simple example using sscanf
to parse the argument:
#include <stdio.h>
int
main(int argc, char **argv)
{
int x, y, d, mm, yyyy;
if( argc > 1 && 3 == sscanf(argv[1], "-/-/M", &d, &mm, &yyyy) ){
printf("%d %d %d\n", d, mm, yyyy);
}
return 0;
}
I would guess you are having issues because your argument does not match the format string, but your program doesn't check the value returned by sscanf
to determine whether or not it successfully read any values into d
, mm
, and yyyy
. Since the variables d
, mm
, and yyyy
are not initialized, your program invokes undefined behavior if sscanf
does not write to them. If it does not write values, then it will return a values less than 3, and your program should catch that condition. Also, your program does not check if argc > 1
or if argv[1] != NULL
, so you have potential undefined behavior even before you pass uninitialized variables to getDateKey
.
In short, validate the input.
CodePudding user response:
In getDataKey
you never initialize the variable key
. The first time you call the function, the value stored at location key
may by pure luck (or unluck) have the initial value of zero, and the function has the illusion of working as expected