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

标签 c arrays char itoa

我有一个自定义 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/

相关文章:

c - 在 C 中使用 strtok()

C++冒泡排序动态分配数组

java - 我无法正确编译此代码。我究竟做错了什么?

java - 表达式的类型必须是数组类型但解析为 char

java - "Find substring in char[]"得到意想不到的结果

c - 如何在宏中编写这样的 if 条件?

命令截断输出的第一行

c - 指针/函数参数问题?

comparison - 字符缓冲区比较

代码厨师 : reverse Polish Notation