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;
    }
}
1
  • Not related to your problem, but fflush(stdin) is almost certainly not what you want. Commented May 2, 2019 at 20:35

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.