0

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

array[0]当我通过简单地访问and来反转数组后打印数组时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);
4

1 回答 1

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循环

}//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;
}
于 2013-04-28T07:55:46.517 回答