【发布时间】:2020-11-20 12:50:19
【问题描述】:
我是 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: %.6f\n", i, j, rows[i][j]);
}
}
}
}
char found[] = "Found";
char apprx[] = "approximate matches.";
printf("%s %d %s\n", found, counter, apprx);
gettimeofday(&tim, NULL);
double t2=tim.tv_sec+(tim.tv_usec/1000000.0);
printf("%.6lf seconds elapsed\n", t2-t1);
}
【问题讨论】:
-
是时候学习使用调试器了。还有一个可以让您的代码保持格式的编辑器。
-
干杯,这就是问题所在,没有 argv[5]
标签: c segmentation-fault