C 获取下面代码的分段错误。我不知道我错在哪里
以下是实现公式(1+x)^2的代码:C 获取下面代码的分段错误。我不知道我错在哪里,c,linux,gcc,C,Linux,Gcc,以下是实现公式(1+x)^2的代码: #包括 #包括 #包括“nCr.h” #包括 #包括 int main(int argc,const char*argv[] { int k=0; int n; INTC; 结构timeval开始、结束; 如果(argv[1][0]='-'&&argv[1][1]=='h'){ printf(“用法:公式”); }否则{ n=atoi(argv[1]); //gettimeofday将以微秒为单位给出程序的执行时间。 gettimeofday(&start,
#包括
#包括
#包括“nCr.h”
#包括
#包括
int main(int argc,const char*argv[]
{
int k=0;
int n;
INTC;
结构timeval开始、结束;
如果(argv[1][0]='-'&&argv[1][1]=='h'){
printf(“用法:公式”);
}否则{
n=atoi(argv[1]);
//gettimeofday将以微秒为单位给出程序的执行时间。
gettimeofday(&start,NULL);
printf(“(1+x)^%i=”,n);
如果(n==0)
printf(“0”);
对于(;k这可能是因为您试图访问不存在的参数。在访问参数之前,请添加argc check。首先使用调试器捕获“正在运行”的崩溃,以定位它在代码中发生的位置。
#include <stdio.h>
#include <stdlib.h>
#include "nCr.h"
#include <time.h>
#include <sys/time.h>
int main(int argc, const char * argv[])
{
int k = 0;
int n;
int c;
struct timeval start, end;
if (argv[1][0] == '-' && argv[1][1] == 'h') {
printf("Usage: formula <positive integer>");
} else {
n = atoi(argv[1]);
// gettimeofday will give the execution time of program in microsecond.
gettimeofday(&start, NULL);
printf("(1 + x)^%i = ", n);
if (n == 0)
printf("0");
for (; k <= n; k++) {
// Here nCr is an assembly code which compute coefficient
c = nCr(n, k);
if (c == -1) {
printf("Multiplication overflow. \n");
return 1;
} else {
if (k != 0)
printf("%i x^%i ",c , k);
if (k != n && k != 0)
printf("+ ");
}
}
gettimeofday(&end, NULL);
}
printf("\n%ld microseconds\n", ((end.tv_sec * 1000000 + end.tv_usec)
- (start.tv_sec * 1000000 + start.tv_usec)));
return 0;
}