Вопрос

1.While I am trying to display conv it is not showing anything, but when i print one one element using subscript i am able to see the contents.
2. Program to convert decimal to binary, octal, hexadecimal

#include<stdio.h>
int main() 
{  
    convbase(23,2);  
    return 0;  
}  
int convbase(int num, int base)  
{  
    char conv[33] = {' '};  
    char *ptr = &conv[32];  
    conv[32] = '\0';  
    do  
    {  
            *--ptr = "0123456789ABCDEF"[num % base];  
             num = num/base;  
    }while(num);  
    if(base == 16)  
    {  
        *--ptr = 'x';  
        *--ptr = '0';  
    }  
    if(base == 8)  
    {  
        *--ptr = '0';  
    }  
    printf("Decimal to base %d is :\t%s\n",base,conv);  
    return 0;  
}  
Это было полезно?

Решение

change

printf("Decimal to base %d is :\t%s\n",base,conv);

to

printf("Decimal to base %d is :\t%s\n",base,ptr);

or

move the contents (ptr - to end of string) to start of conv array

another alternative is to instead of writing from end of conv to write from start and then when you are done call strrev() to reverse it.

printf("Decimal to base %d is :\t%s\n",base,strrev(conv));

Другие советы

You are filling your array from the end towards the front. In your example, the bit string is in the array elements 27...31. Thus, the 1st element contains \0, and the char array will be considered as an empty string, and nothing is printed. You can check this easily by setting a breakpoint at the print statement.

You most propably assume that the following line initialises conv to all blanks:

char conv[33] = {' '}; 

This is not the case. With the above code conv has its first byte set to blank and all other bytes set to 0. So the result would only be printed if it had at least 31 digits.

You might consider using the follwong code to intialise conv:

char conv[33] = {0};  /* default init: set conv to all zeros */
memset(conv, ' ', sizeof(conv) - 1); /* re-set all but the last to blank */

This line:

conv[32] = '\0'; 

is not needed anymore than.


I do agree with Reinhard Männer that using a debugger would have helped you a lot to finding this out by yourself.

I think you're doing one -- too much.

While building the string, ptr always points to where you're going to write the next character (if there is a next character). This place is always initialized with null bytes (except for conv[0], which is a space.
So when calling printf, ptr points to null bytes, which is an empty string.

ptr++ before printf should solve it.

I do agree with @alk.

You were initializing only the first element of the array with blank and other elements were initialized to 0 because of which you were getting blank line. Actually line is not blank, printf prints only first character which is blank ' ' and when it encounter 0 it stops.

You can verify it by replacing ' ' with any other character. ofcourse except '\0'

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top