0

I have problem with this project, i try to search an answer on forum but i didn't found nothing.

struct orario {
int hours;
int minutes;
int seconds;
char *format;
}orario1;

int main(int argc, char *argv[]) {
sscanf(argv[1],"%d:%d:%d %s",&orario1.hours,&orario1.minutes,&orario1.seconds,orario1.format);

printf("%d:%d:%d %s",orario1.hours,orario1.minutes,orario1.seconds,orario1.format);

The output is correct for the numerical part but the string(for example AM or PM) is unexpected (null).

I can't recognize my error, can someone find and tell me?!

Thank you.

alk
  • 69,737
  • 10
  • 105
  • 255
Fabio
  • 336
  • 3
  • 17
  • You should really check if the user provided one (or more) arguments before using `argv[1]` etc. If no arguments were provided then `argv[1]` will be a null pointers, and `argv[2]` and up will be out of bounds. This check is done by testing that `argc >= 2`. – Some programmer dude Aug 14 '17 at 13:48
  • Yes i know, i will do it. – Fabio Aug 14 '17 at 14:06

1 Answers1

1

Your code has undefined behavior, since format is an uninitialized pointer.

Use

char format[8];

and %7s. And check the return value before relying on the variables having values.

unwind
  • 391,730
  • 64
  • 469
  • 606