简体   繁体   English

带字符串的 Printf 不起作用(2 种方式:函数返回值和一个值)

[英]Printf with string does not work(2 ways: function return value and just a value)

So, my problem is whenever I want to print %s (char *), the program shows an empty string.所以,我的问题是每当我想打印 %s (char *) 时,程序都会显示一个空字符串。 Here is my code and I numbered all the questions inside the comments in the program这是我的代码,我对程序注释中的所有问题进行了编号

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *decToBinary(char *num, int size);

int main(){
    char *n;
    n = (char *)malloc(5);  
    //memset(n, 0, 5);
    printf("Enter n: ");

    // getting the number as a string
    scanf("%s", n);
    int size = 33;
    char *binNum;
    binNum = (char *)malloc(size);  
    memset(binNum, 0, size);

    //copying the (char *) which is returned by function to char binNum[33] 
    strcpy(binNum, decToBinary(n, size));

    //sprintf(binNum, "%s", decToBinary(n, size));

    // Printing the FUNCTION variable as a character in a loop. WORKS(WHY?)(3)
    for(int i = 0; i < size; i++){
        printf("With function: %c", decToBinary(n, size)[i]);
    }
    //Printing the variable binNum as a string <--------- DOES NOT WORK. JUST EMPTY MESSAGE(WHY?)(4)
    printf("In main: %s\n", binNum);

    // Printing the variable binNum as a character in a loop <------------ DOES NOT WORK(5)
    for(int i = 0; i < size; i++){
        printf("with variable: %c", binNum[i]);
    }
    printf("\n");
}

char *decToBinary(char *num, int size){
    // convert decimal to binary
    int i = size - 2;
    int remainder;
    int decimal;
    char *binary;
    int n;
    n = atoi(num); 
    binary = (char *)malloc(size);
    binary[size - 1] = '\0';
    memset(binary, 0, size);
    do{
        remainder = n % 2;
        n /= 2;
        binary[i] = remainder + '0';
        i--;
    }while(n);
    printf("decToBinary = %s\n", binary); // does not work as string (1)
    for(int j = 0; j < size; j++){
        printf("%c", binary[j]); // but this works(2)
    }
    printf("\n");
    return binary;   
}
  • (1) The string is not displayed in the function. (1) 函数中不显示字符串。 Even if I flush the buffer by using "\\n"即使我使用 "\\n" 刷新缓冲区
  • (2) But when I use "for" loop and display each element of the array using %c - it works. (2) 但是当我使用“for”循环并使用 %c 显示数组的每个元素时 - 它可以工作。 But this is not a good way to make it work但这不是让它工作的好方法
  • (3) In main() function printf of every element of return value from the function works fine even though I do not get the idea how it can work, because as I understood,the function is invoked 33 times and the value is returned 33 times and here I just read one element by one. (3) 在 main() 函数中,函数返回值的每个元素的 printf 工作正常,即使我不知道它是如何工作的,因为据我所知,该函数被调用了 33 次,返回值是 33次,在这里我只是一个一个地阅读。 That's bad practice I think.我认为这是不好的做法。
  • (4) So I copied the returned value from function to the variable binNum and tried to display it using %s, but again empty string is displayed. (4) 所以我将函数的返回值复制到变量 binNum 并尝试使用 %s 显示它,但再次显示空字符串。
  • (5) Same thing with variable but using "for" loop and %c. (5) 与变量相同,但使用“for”循环和 %c。 Also did not work也没有工作

So, my question is how to manage these problems?所以,我的问题是如何管理这些问题?

If you change your code a bit如果你稍微改变你的代码

    for(int j = 0; j < size; j++){
        printf("%c 0x%02x\n", binary[j], binary[j]); // but this works(2)
    }

you will see the leading '\\0' in your result:您将在结果中看到领先的'\\0'

With function: 1decToBinary =
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
1 0x31
0 0x30
0 0x30
0 0x30
0 0x30
0 0x30
0 0x30
0 0x30
0 0x30
1 0x31
1 0x31
 0x00

So there is something wrong in your function decToBinary .所以你的函数decToBinary

You count with i from the end of the array, so depending on the input you may not reach the beginning of the array.您从数组的末尾用i计数,因此根据输入,您可能无法到达数组的开头。

You can try return binary+i+1;你可以试试return binary+i+1; at the end of decToBinary .decToBinary This will return a pointer to the character you have written last.这将返回一个指向您最后写入的字符的指针。 Note that you should not iterate over size characters of the result but only up to a '\\0 .请注意,您不应迭代结果的size字符,而应迭代到'\\0

This is not the final solution because you use malloc to allocate the character array in decToBinary .这不是最终的解决方案,因为您使用mallocdecToBinary分配字符数组。 This means you should return the pointer you got from malloc and call free in the calling function.这意味着您应该返回从malloc获得的指针并在调用函数中调用free

To allow this you can use an additional loop that copies all characters from index i+1 up to a '\\0' to the start of the array.为此,您可以使用一个额外的循环,将索引i+1'\\0'所有字符复制到数组的开头。

    for(i++, j=0; binary[i]; i++, j++) {
        binary[j] = binary[i];
    }
    binary[j] = '\0';

    /* ... */

    return binary;

Additional note:补充说明:

Code like this creates a memory leak because you don't free the results of repeated calls to decToBinary :像这样的代码会造成内存泄漏,因为您不会free重复调用decToBinary的结果:

    for(int i = 0; i < size; i++){
        printf("With function: %c", decToBinary(n, size)[i]);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM