Printing array of characters returned from functio

2019-09-21 03:27发布

问题:

I'm a newbie in C language, so forgive me the beginners question.

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

char *decimal_to_binary(int);

void main() {
    int buffer;

    while (1) {
        printf("Type your number here: \n\r");
        scanf_s("%d", &buffer);
        printf("After conversion to binary system your number is: \n\r");
        printf("%s", decimal_to_binary(buffer));
        printf("\n");
    }
}

int get_byte_value(int num, int n) {
    // int x = (num >> (8*n)) & 0xff
    return 0;
}

char* decimal_to_binary(int num) {
    int tab[sizeof(int) * 8] = { 0 };
    char binary[sizeof(int) * 8] = { 0 };
    int i = 0;

    while (num) {
        tab[i] = num % 2;
        num /= 2;
        i++;
    }

    for (int j = i - 1, k = 0; j >= 0; j--, k++) {
        binary[k] = tab[j];
    }

    return binary;
}

When I print out whatever came back from decimal_to_binary I get some garbage (a smiley face character) instead of the binary representation. But when I do printf inside the last loop of the decimal_to_binary function, I'm getting correct values. So what did I do wrong?

回答1:

This

char binary[sizeof(int) * 8] = { 0 };

is a local variable declaration, you can't return that.

You need to use the heap to return an array from a function, for that you need malloc()

char *binary; /* 'binary' is a pointer */
/* multiplying sizeof(int) will allocate more than 8 characters */
binary = malloc(1 + 8);
if (binary == NULL)
    return NULL;
binary[sizeof(int) * 8] = '\0'; /* you need a '\0' at the end of the array */
/* 'binary' now points to valid memory */

Next the assignment binary[k] = tab[j]; is probably not what you think

binary[k] = (char)(tab[j] + '0');

would likely be what you want.

note: strings in c are just sequences of bytes with a terminating '\0'.

After fixing this, you need to fix main() too, doing this now

printf("%s", decimal_to_binary(buffer));

is wrong, because decimal_to_binary() could return NULL, and because you need to free the buffer after it's returned, so

char *binstring = decimal_to_binary(buffer);
if (binstring != NULL)
    printf("%s", binstring);
free(binstring);

also, notice that you are only computing 8 bits, so an appropriate signature for decimal_to_binary would be

char *decimal_to_binary(int8_t value);


标签: c arrays printf