我对 C 编程还比较陌生,并且遇到了以前从未见过的错误。我编写了一个程序,它接受两个整数,并根据第二个输入将第一个整数转换为其各自的基数形式。我不是在问如何解决问题,我只是在问我哪里出了问题而收到此错误。我做了一些研究,知道段错误与指针有关,并且我已经尝试过我的方法,但没有运气摆脱这个错误。任何帮助将不胜感激!
#include<stdio.h>
void decimalToRadix(int d, int r, char *toRadix);
int main(void){
int decimal, radix;
char toRadixForm[100];
printf("Enter a decimal number: ");
scanf("%d",&decimal);
printf("Enter radix number: ");
scanf("%d",radix);
decimalToRadix(decimal, radix, toRadixForm);
puts("");
return 0;
}
void decimalToRadix(int decimal, int radix, char *toRadix){
int result;
int i=1,x,temp;
result=decimal;
//will loop until result is equal to 0
while(result!=0){
//get the remainder
temp=result%radix;
//if<10 add 48 so character format stored values are from 0-9
if(temp<10)
temp=temp+48;
//if greater that or equal to 10 add 55 to it stores values A-Z
else
temp=temp+55;
toRadix[i++]=temp;
result=result/radix;
}
printf("The value of the number you entered, %d, to radix form is ", decimal);
for(x=i-1; x>0; x--){
printf("%c", toRadix[x]);
}
最佳答案
我猜您收到此消息的原因可能是由于拼写错误。第 14 行的 scanf 参数列表中缺少 &
。您应该这样做:scanf("%d",&radix);
。您收到段错误是因为 scanf 需要它应该读取的变量的内存地址;因为这是在变量作用域之外更改变量的唯一方法。但是您正在传递 scanf("%d", radix)
,在这种情况下 radix 可以包含 0 或任何垃圾值。当您的程序尝试访问该程序不应读取的内存地址时,操作系统会终止该程序,并给出 Segmentation Fault 。更改此设置后,我得到了输出:
~/Documents/src : $ ./a.out
Enter a decimal number: 12
Enter radix number: 2
The value of the number you entered, 12, to radix form is 1100
关于C 程序 - 接收段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43713545/