gpt4 book ai didi

c - 以文本格式打印数字的数字

转载 作者:太空宇宙 更新时间:2023-11-04 03:44:26 25 4
gpt4 key购买 nike

所以我一直在尝试用 c 语言编写这段代码,其中的基本思想是用户输入一个正整数,然后程序打印出该数字中的数字,我已经递归地完成了它,但事情是,当我编译它时,我没有得到任何错误,但输出只是一些垃圾,另一方面,我试过调试,所以我设置了一些断点,我一直在得到很好的结果,并在调试时纠正输出,与尝试编译完全相同的代码段时不同如果有人知道为什么会这样,我们将不胜感激

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

char *numToWord (int number){
char *newDigit = NULL;
switch(number){
case 0:
newDigit = malloc (5*sizeof(char));
sprintf(newDigit,"zero");
break;
case 1:
newDigit = malloc (4*sizeof(char));
sprintf(newDigit,"one");
break;
case 2:
newDigit = malloc (4*sizeof(char));
sprintf(newDigit,"two");
break;
case 3:
newDigit = malloc (6*sizeof(char));
sprintf(newDigit,"three");
break;
case 4:
newDigit = malloc (5*sizeof(char));
sprintf(newDigit,"four");
break;
case 5:
newDigit = malloc (5*sizeof(char));
sprintf(newDigit,"five");
break;
case 6:
newDigit = malloc (4*sizeof(char));
sprintf(newDigit,"six");
break;
case 7:
newDigit = malloc (6*sizeof(char));
sprintf(newDigit,"seven");
break;
case 8:
newDigit = malloc (6*sizeof(char));
sprintf(newDigit,"eight");
break;
case 9:
newDigit = malloc (5*sizeof(char));
sprintf(newDigit,"nine");
break;
}
return newDigit;
}

char * writeAbsolute (int number) {
char * word = NULL; // variable where the return value will be stored, must clean in main part
int digit;
digit = number % 10;
if (number){
number /= 10;
word = writeAbsolute (number);
char *newDigit = NULL;
char *newWord = NULL;
newDigit = numToWord(digit);
if (word){
int numOfLetters = (int)( strlen(newDigit)+strlen(word) );
newWord = (char*) malloc(numOfLetters * sizeof(char));
sprintf(newWord,"%s %s",word,newDigit);
word = newWord;
}
else{
word = newDigit;
}
free (newWord);
free (newDigit);
}
return word;
}


int main() {
int number;
char * word;
printf("Enter an integer:\n");
scanf("%d",&number);
word = writeAbsolute(number);
printf("%s",word);
return 0;
}

最佳答案

第一个问题是您没有为所有字符串分配足够的内存。由于固有的尾随 '\0' 终止字节,字符串 "1234" 应分配 5 个字符。只需将至少一个添加到所有字符串分配长度:

newDigit = malloc(5*sizeof(char));
sprintf(newDigit,"six ");
...
int numOfLetters = (int) (strlen(newDigit) + strlen(word) + 1);

另请注意,sizeof(char) 被定义为 1

第二个问题是您在此代码中使用字符串后立即释放它们:

if (word) {
...
newWord = (char *) malloc(...);
...
word = newWord;
}
else {
word = newDigit;
}

free (newWord);
free (newDigit);

假设 word 不是 NULL,当你在最后释放 newWordword 变得无效,因为它只是指向同一个字符串。因此,下次您尝试使用 word 时,您会通过尝试使用之前释放的内存来调用未定义的行为。

在这种情况下,您可能想要的是:

if (word) {
int numOfLetters = (int)( strlen(newDigit)+strlen(word) + 1);
newWord = (char*) malloc(numOfLetters);
sprintf(newWord,"%s%s", word, newDigit);
word = newWord;
free(newDigit);
}
else {
word = newDigit;
}
// Don't free anything else here

关于c - 以文本格式打印数字的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25953465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com