我已经看到使用指针解决此问题的其他解决方案。我不太了解指针的工作原理,无法将它们实现到该程序中。如果解决方案需要一个,有人可以解释为什么吗?我整晚都在用这个程序尝试各种事情,但一无所获。我阅读了“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;
}
最佳答案
如果我错了,有人纠正我。但是您没有在 char 数组中放置空终止符:
for(i=0; i<MAX && (c=getchar())!=EOF && c != '\n'; ++i)
line[i] = c;
稍后,你会做
for(i=0; s[i] != '\0'; ++i)
但是由于您从未附加空终止符,因此上面的 for 循环将遍历数组的边界,直到它在堆栈的某处看到空值或出现段错误。
您应该执行以下操作:
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
关于c - 程序在将十六进制转换为整数时打印内存地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18020531/