0

I have this code example and i can't figure out why sscanf works like intended in the example function but not in the main function.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void example(char *seq){
    char wert;
    while(*seq){
        sscanf(seq,"%2x",&wert);
        fprintf(stdout,"%c",wert);
        seq+=2;
    }
}

int main() {
    char temp;
    char sentence []="1B2873313648";
    char *seq=sentence;
    example(seq);
    printf("\n");
    while(*seq){
        sscanf(seq,"%2x",&temp);
        fprintf(stdout,"%c",temp);
        seq+=2;
    }
}
  • Not related to your problem, but `fflush(stdin)` is almost certainly [not what you want](https://stackoverflow.com/questions/2979209/using-fflushstdin?noredirect=1&lq=1). – Nate Eldredge May 02 '19 at 20:35

1 Answers1

4

The sscanf format specifier %x is expecting a pointer to unsigned int, not a pointer to char, so all bets are off due to undefined behaviour. Please take note of the compiler warnings. On my MSVC this code causes a crash.

This corrected code works.

#include <stdio.h>          // missing
#include <stdlib.h>
#include <string.h>

void example(char *seq){
    unsigned wert;
    while(*seq){
        sscanf(seq,"%2x",&wert);
        fprintf(stdout,"%02X ",wert);
        seq+=2;
        //fflush(stdin);
    }
}

int main() {
    unsigned temp;
    char sentence []="1B2873313648";
    char *seq=sentence;
    example(seq);
    printf("\n");
    while(*seq){
        sscanf(seq,"%2x",&temp);
        fprintf(stdout,"%02X ",temp);
        seq+=2;
        //fflush(stdin);
    }
}

Program output:

1B 28 73 31 36 48
1B 28 73 31 36 48
Weather Vane
  • 33,872
  • 7
  • 36
  • 56