【发布时间】:2014-06-02 23:52:39
【问题描述】:
我是 C 编程的新手(只用了 2 周)。我无法弄清楚为什么我的代码会引发分段错误。如果我将 long int num 设置为一个静态数字,我就能让程序工作。但是我需要程序能够接受来自命令行的用户输入(不是在程序运行后)
示例: ./binary 7
应该输出 7的二进制数是:111
我尝试过使用 strcpy(num, argv[0]) 但编译时也会抛出错误。
#include<stdio.h>
#include <string.h>
#include<math.h>
void decToBinary(long int num) // Function Definition
{
long int remainder[50];
int i=0;
int length=0;
printf("The binary number for %d is: ",num);
while(num > 0)
{
remainder[i]=num%2; // does the mod function
num=num/2; // Divides original number by 2
i++; // Increases count for the upcoming for-loop
length++; // Increases length display digits
}
for(i=length-1;i>=0;i--) // Prints out the binary number in order (ignoring the previous 0's)
{
printf("%ld",remainder[i]);
}
printf("\n"); // Adds a new line after the binary number (formatting)
}
//================================================================================================
int main(char argc, char* argv[])
{
long int num; //HOW DO I TAKE ARGV[0] AND MAKE IT A USEABLE VARIABLE???
printf("Enter the decimal number: "); //TEMPORARY until problem above is solved
scanf("%ld",&num); //TEMPORARY until problem above is solved
decToBinary(*num); // Calling decToBinary function
return 0; // Program terminated successfully
}
【问题讨论】:
-
如果您是 C 新手,那么您的第一个致命错误就是您正在丢弃
scanf的返回值。您的第二个致命错误是您忽略了编译器的警告,或者更糟糕的是,没有指示您的编译器警告您明显的错误(例如*num)。 -
Ideone 出于三个不相关的原因放弃了您的代码。
标签: c pointers binary segmentation-fault