gpt4 book ai didi

c - itoa 函数不适用于单位数整数

转载 作者:行者123 更新时间:2023-11-30 15:49:28 28 4
gpt4 key购买 nike

我有一个自定义 itoa 函数,适用于 10 及更大的整数,但由于某种原因,如果传递的整数是单个数字,它不会返回任何内容。我似乎不明白为什么会这样。

当我通过简单地访问 array[0] 来反转数组后打印数组时和array[1] ,我看到 null 和单个数字打印得很好,但在单个数字后面有一些奇怪的尾随字符。这只发生在个位数上。例如(blank)7e(blank)4r

功能:

 char* customitoa(int number, char * array, int base){

array[0] = '\0';

int quotient = number, i = 1;

/* stores integers as chars into array backwards */

while(quotient != 0){
int temp, length = 1;
temp = quotient % base;

length++;
array = realloc(array, (length)*sizeof(char));

if (temp <= 9){
array[i++] = (char)(((int)'0')+temp);
} else {
array[i++] = (char)(temp + ('A' - 10));
}
quotient = quotient / base;

}

/* reverse array*/
int j; int k;
k = 0;
j = i - 1;
char temp;
/* - different swap functions based on odd or even sized integers */
if( (j%2) == 1){

while((k <= ((j/2)+1))){
temp = array[k];
array[k] = array[j];
array[j] = temp;
k = k+1;
j = j - 1;
}
} else {
while(k <= (((j)/2))){
temp = array[k];
array[k] = array[j];
array[j] = temp;
k = k+1;
j = j - 1;
}
}

return array;
}

在此上下文中调用该函数:

char *array;
array = malloc(length*sizeof(char));

array = myitoa(number, array, base);

printf("%s", array);

free(array);

最佳答案

while(quotient != 0){
int temp, length = 1;

在此循环中长度始终为 1。

更改为

int length = 1;
while(quotient != 0){
int temp;

最后执行一次realloc

array = realloc(array, (length)*sizeof(char));

移出while循环

}//while end
array = realloc(array, (length)*sizeof(char));

下列条件不正确

while((k <= ((j/2)+1))){ 
....
while(k <= (((j)/2))){

更改为

int L = j/2;
...
while(k <= L){
...
while(k <= L-1){

总结一下

if( j%2 == 1)
L=j/2;
else
L=j/2-1;
while(k <= L){
temp = array[k];
array[k] = array[j];
array[j] = temp;
k = k+1;
j = j - 1;
}

关于c - itoa 函数不适用于单位数整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16258416/

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