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