-3

I'm trying to convert decimal to binary. I'm working on function "const char * dtb_16(float a)". in this function, I'm returning the pointer of the string as code below.

code segment

OR

const char* dtb_16(float a) {
    char str[17];
    int i = 0;;
    for (i = 0; i < 16; i++) {
        a = a * 2;
        if (a > 1) {
            a = a - 1;
            str[i] = '1';
        }
        else
            str[i] = '0';
    }
    str[16] = 0;
    printf("%s \n", str);;
    return str;
}

and at main

printf("test : %s\n", dtb_16(decimal));

the result is something like this:

starting read files
Please enter binary bit length: 16
0011101011100001
test : 烫烫眺?
1011110101110000
test : 烫烫眺?
1110001111010111
test : 烫烫眺?
1101110000101000
test : 烫烫眺?
1001100110011001

the string looks fine in the function dtb_16 but it goes wrong when back to main. I tried return *str and &str, none of them works.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
高VICTOR
  • 3
  • 2

1 Answers1

1

You shouldn't return an address of a local variable, instead you will have to create the str variable on the heap. You can do that by swapping char str[17]; to char* str = malloc(sizeof(char) * 17);

czarson
  • 125
  • 7