chanjianyi
chanjianyi

Reputation: 615

hex arrary to char* string in C

After got the answer from this question: char* string to hex arrary in C

I wrote a function:

u8 * mac_char_to_hex(char * mac){
    static u8 m[6]; 
    sscanf(mac, "%2x%2x%2x%2x%2x%2x", (int *)&m[0], (int *)&m[1], (int *)&m[2], (int *)&m[3], (int *)&m[4], (int *)&m[5]);
    return m;
}

it working well, then I want to write a reverse function, look like:

char * mac_hex_to_char(u8 m[]) {
    static char * mac;
    sprintf((char *) mac, "%2x%2x%2x%2x%2x%2x", (int *)&m[0], (int *)&m[1], (int *)&m[2], (int *)&m[3], (int *)&m[4], (int *)&m[5]);
    printf("---------%s-------\r\n",mac);
    return mac;
}

so what's the problem?

Upvotes: 0

Views: 132

Answers (2)

harper
harper

Reputation: 13690

That's undefined behavior. Your variable mac is not initialized. Additionally you don't want to fiddle with a pointer. Use this instead:

char * mac_hex_to_char(u8 m[]){

    static char mac[6*2 + 1];
    sprintf(mac, "%2x%2x%2x%2x%2x%2x", m[0], m[1], m[2], m[3], m[4], m[5]);
    return mac;
}

Upvotes: 1

chanjianyi
chanjianyi

Reputation: 615

finally, I got the right function after read @harper answer. and do some modify:

char * mac_hex_to_char(u8 m[]){
    static char  mac[6*2+1];
    sprintf(mac, "%2x%2x%2x%2x%2x%2x", m[0], m[1], m[2], m[3],m[4], m[5]);
    return mac;
}

Upvotes: 0

Related Questions