[英]C Program - Receiving Segmentation Fault
我對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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.