سؤال

I have a custom itoa function that works for integers 10 and greater, but for some reason it returns nothing if the integer passed is a single digit. I can't seem to figure out why that is.

When I print the array after it has been reversed by simply accessing array[0] and array[1], I see that a null and that single digit is printed fine, but there is some weird trailing character after the single digit. This only happens for single digits. for example (blank)7e or (blank)4r

The function:

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

The function is called in this context:

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

array = myitoa(number, array, base);

printf("%s", array);

free(array);
هل كانت مفيدة؟

المحلول

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

length is always 1 in this loop.

change to

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

realloc is performed once at the end

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

move outside while loop

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

The following conditions is incorrect

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

change to

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

To summarize in one

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;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top