程序在将十六进制转换为整数时打印内存地址

时间:2013-08-02 15:19:15

标签: c hex

我已经看到了使用指针的这个问题的其他解决方案。我不明白指针的工作方式足以将它们实现到这个程序中。如果解决方案需要一个,请有人能解释原因吗?我一直在用这个程序尝试各种各样的事情并且无处可去。我阅读了“The C Programming Language”一书中的相关文字,其中的练习来自。我不能成为唯一被这个D难倒的人:

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

#define MAX 1000

int htoi(char s[]);


main()
{
char line[MAX];
int i, c;
printf("Enter the strig to convert to an integer:");
for(i=0; i<MAX && (c=getchar())!=EOF && c != '\n'; ++i)
    line[i] = c;
int a =0;
a = htoi(line);
printf("%d", a);

}  

int htoi(char s[])
{
int i, n, z;
n=0;
int total = 0;
for(i=0; s[i] != '\0'; ++i)
    {
        if (s[i] == 'a'||s[i] == 'A')
            n = 10;
        else if(s[i] == 'b'||s[i] == 'B')
            n = 11;
        else if(s[i] == 'c'||s[i] == 'C')
            n = 12;
        else if(s[i] == 'd'||s[i] == 'D')
            n = 13;
        else if(s[i] == 'e'||s[i] == 'E')
            n = 14;
        else if(s[i] == 'f'||s[i] == 'F')
            n = 15;
        else
            n = s[i];
        z = n * pow(16, i);
        total = total + z;
    }
return total;
}

2 个答案:

答案 0 :(得分:2)

如果我错了,有人会纠正我。但是你没有在char数组中放置一个null终止符:

for(i=0; i<MAX && (c=getchar())!=EOF && c != '\n'; ++i)
   line[i] = c;

稍后,你做

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

但是由于你从未附加一个空终止符,上面的for循环将迭代PAST数组的边界,直到它在堆栈的某个地方看到null或者它是段错误。

你应该做以下事情:

for(i=0; i<(MAX-1) && (c=getchar())!=EOF && c != '\n'; ++i)
   line[i] = c;
line[i+1] = '\0';

请注意(MAX-1)

P.S不要以root身份运行不需要root的任何内容,请参阅:least privilege principle

答案 1 :(得分:0)

你的问题在这里:

else
        n = s[i]; // <- n is getting the character code value of S[i]

要解决,我建议:

else
        n = s[i] - '0';

<强>编辑:

你还有两个问题:

  1. 你需要null终止行char(你的字符串没有'\ 0')
  2. 你正在反转功率数学(左边的数字比右边的数字更重要)
  3. 要解决(1),请执行以下操作:

    for(i=0; i<MAX && (c=getchar())!=EOF && c != '\n'; ++i)
        line[i] = c;
    line[i] = '\0'; // <-- added here
    

    要解决(2),请执行以下操作:

    int total = 0;
    int len = strlen(s) - 1; // <- added here
    ...
    z = n * pow(16, len - i); // <- change here
    

    另一种方法是,你可以避免使用昂贵的pow功能,只需将4位向左移动,如下面的代码所示:

    而不是:

    z = n * pow(16, i);
    total = total + z;
    

    做的:

    total <<= 4;  // changed here
    total += n;   // and here