打印从C函数返回的字符数组 [英] Printing array of characters returned from function in C

查看:49
本文介绍了打印从C函数返回的字符数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C语言的新手,所以请您谅解初学者的问题.

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;
}

当我打印出从decimal_to_binary返回的所有内容时,我得到了一些垃圾(笑脸字符)而不是二进制表示形式.但是,当我在 decimal_to_binary 函数的最后一个循环中执行 printf 时,我得到的是正确的值.那我做错了什么?

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?

推荐答案

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

是局部变量声明,您不能返回它.

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

您需要使用堆从函数返回数组,为此您需要 malloc()

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 */

接下来,分配 binary [k] = tab [j]; 可能不是您所想的

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

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

可能就是您想要的.

注释:c中的字符串只是带有终止符'\ 0'的字节序列.

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

修复此问题后,您还需要修复 main(),现在就执行此操作

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

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

是错误的,因为 decimal_to_binary()可能返回 NULL ,并且因为您需要在缓冲区返回后释放它,所以

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);

另外,请注意,您只计算 8 位,因此 decimal_to_binary 的适当签名应为

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函数返回的字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆