[英]Printf with string does not work(2 ways: function return value and just a value)
所以,我的問題是每當我想打印 %s (char *) 時,程序都會顯示一個空字符串。 這是我的代碼,我對程序注釋中的所有問題進行了編號
#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;
}
所以,我的問題是如何管理這些問題?
如果你稍微改變你的代碼
for(int j = 0; j < size; j++){
printf("%c 0x%02x\n", binary[j], binary[j]); // but this works(2)
}
您將在結果中看到領先的'\\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
所以你的函數decToBinary
。
您從數組的末尾用i
計數,因此根據輸入,您可能無法到達數組的開頭。
你可以試試return binary+i+1;
在decToBinary
。 這將返回一個指向您最后寫入的字符的指針。 請注意,您不應迭代結果的size
字符,而應迭代到'\\0
。
這不是最終的解決方案,因為您使用malloc
在decToBinary
分配字符數組。 這意味着您應該返回從malloc
獲得的指針並在調用函數中調用free
。
為此,您可以使用一個額外的循環,將索引i+1
到'\\0'
所有字符復制到數組的開頭。
for(i++, j=0; binary[i]; i++, j++) {
binary[j] = binary[i];
}
binary[j] = '\0';
/* ... */
return binary;
補充說明:
像這樣的代碼會造成內存泄漏,因為您不會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.