itoa函数不适用于单个数字的整数

时间:2013-04-28 00:47:52

标签: 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);

1 个答案:

答案 0 :(得分:1)

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

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

更改为

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

realloc最后执行一次

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

在循环中移动到外面

}//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;
}