Home > Blockchain >  K&R C Programming Language Exercise 2-3 code returns rubbish
K&R C Programming Language Exercise 2-3 code returns rubbish

Time:01-03

I tried to write a solution from exercise 2-3. After compilation, it returns random numbers on output. I don't really understand where this issue is coming from.

Any help appreciated.

StackOverflow keeps asking for more details. The purpose of the program is listed in the code bellow.

More delails.

Purpose of the code:

Write the function htoi(s), which converts a string of hexa- decimal digits (including an optional 0x or 0X) into its equivalent integer value. The allowable digits are 0 through 9, a through f, and A through F.

/*
 * Write the function htoi(s), which converts a string of hexa-
 * decimal digits (including an optional 0x or 0X) into its
 * equivalent integer value. The allowable digits are 0 through 9,
 * a through f, and A through F.
*/

#include <stdio.h>
#include <math.h>

int hti(char s)
{
        const char hexlist[] = "aAbBcCdDeEfF";
        int answ = 0;
        int i;

        for (i=0; s != hexlist[i] && hexlist[i] != '\0'; i  )
                ;
        if (hexlist[i] == '\0')
                answ = 0;
        else
                answ = 10   (i/2);
        return answ;
}

unsigned int htoi(const char s[])
{
        int answ;
        int power = 0;
        signed int i = 0;
        int viable = 0;
        int hexit;

        if (s[i] == '0')
        {
                i  ;
                if (s[i] == 'x' || s[i] == 'X')
                        i  ;
        }
        const int stop = i;

        for (i; s[i] != '\0'; i  )
                ;
        i--;

        while (viable == 0 && i >= stop)
        {
                if (s[i] >= '0' && s[i] <= '9')
                {
                        answ = answ   ((s[i] - '0') * pow(16, power));
                }
                else
                {
                        hexit = hti(s[i]);
                        if (hexit == 0)
                                viable = 1;
                        else
                        {
                                hexit = hexit * (pow(16, power));
                                answ  = hexit;
                        }
                }
                i--;
                power  ;
        }
        if (viable == 1)
                return 0;
        else
                return answ;
}

int main()
{
        char test[] = "AC";
        int i = htoi(test);
        printf("%d\n", i);
        return 0;
}

CodePudding user response:

answ is not initialized in htoi. Initialize it to zero.

  • Related