我是C的新手,所以如果这很明显的话,我会这么做,但在过去的一个半小时里,我一直在努力寻找这个分段错误。我一直在注释代码的各个部分,试图找到它。但当我修复我认为错误的部分时,分段错误仍然存在。我一直在搜索的代码如下。如有任何帮助,我们将不胜感激。起初我以为这是计数器的问题,但后来看起来更像是排。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
#include "utils.h"
int main(int argc, char* argv[])
{
struct tm *local;
struct tm *local2;
time_t start, end;
time(&start); // read and record clock
local = localtime(&start);
struct timeval tim;
gettimeofday(&tim, NULL);
double t1=tim.tv_sec+(tim.tv_usec/1000000.0);
printf("# Start time and date: %s", asctime(local));
float refVal;
float tolVal;
int vFirst, vSecond;
vFirst = (strcmp(argv[1], "-v") == 0);
vSecond = (strcmp(argv[5], "-v") == 0);
int rct;
int cct;
int j;
float row = 0;
int r;
int c;
int counter=0;
int refFirst;
int v = 0;
scanf("%d %d",&rct,&cct);
if(vFirst){
v = 1;
refFirst = (strcmp(argv[2], "-r")== 0);
if(refFirst){
refVal = strtof(argv[3], NULL);
tolVal = strtof(argv[5], NULL);
}else{
tolVal = strtof(argv[3], NULL);
refVal = strtof(argv[5], NULL);
}
}else if(vSecond){
v = 1;
refFirst = (strcmp(argv[1], "-r")== 0);
if(refFirst){
refVal = strtof(argv[2], NULL);
tolVal = strtof(argv[4], NULL);
}else{
tolVal = strtof(argv[2], NULL);
refVal = strtof(argv[4], NULL);
}
}else{
refFirst = (strcmp(argv[1], "-r") == 0);
if(refFirst){
refVal = strtof(argv[2], NULL);
tolVal = strtof(argv[4], NULL);
}else{
tolVal = strtof(argv[2], NULL);
refVal = strtof(argv[4], NULL);
}
}
float** rows = (float **) malloc(rct * sizeof(float *));
if (rows == 0)
{
fprintf(stderr, "Couldn’t alocate sufficient space.n");
exit(1);
}
int i;
for (i = 0; i < rct; i++)
{
float* row = (float *) malloc(cct * sizeof(float));
if (row == 0)
{
fprintf(stderr, "Couldn’t alocate sufficient row space.n");
exit(1);
}
rows[i] = row;
}
for(i = 0; i < rct; i++)
{
for(j = 0; j < cct; j++)
{
scanf("%f", &rows[i][j]);
}
}
for(i = 0; i < rct; i++)
{
for(j = 0; j < cct; j++)
{
if(approxEqual(rows[i][j], refVal, tolVal)){
counter++;
if(v != 1){
fprintf(stdout, "r=%d, c=%d: %.6fn", i, j, rows[i][j]);
}
}
}
}
char found[] = "Found";
char apprx[] = "approximate matches.";
printf("%s %d %sn", found, counter, apprx);
gettimeofday(&tim, NULL);
double t2=tim.tv_sec+(tim.tv_usec/1000000.0);
printf("%.6lf seconds elapsedn", t2-t1);
}
解决方案已在注释中确定,但作为处理command-line
输入相关错误的建议,在使用command-line
输入时,最好包含一个小的用法语句,以提醒用户(包括您自己(如果在没有正确数量/类型的参数的情况下调用可执行文件。
简单示例:
int main(int argc, char* argv[])
{
if(argc != 6)
{
printf("argc == %d, expected 6.n"Usage: some.exe <arg1> <arg2> ... <arg_n>nProgram will now exit.", argc);
return 0;
}
...