【发布时间】:2014-03-04 01:57:32
【问题描述】:
我只需要一双额外的眼睛来帮助我找出这段代码为什么会出现段错误。
//------------------------Preprocessor Instructions. ------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#define NUMBER 128 //Maxmimum number of items/lines in file.
#define BUFFER 120 //Buffer length (For user input)
#define LENGTH 32 //Maximum length of lines in file.
//------------------------Global stuff. ---------------------------------------------
int iterations=0; //Will count number of times the calculation function is called.
int weight[NUMBER];
int value[NUMBER];
char object[NUMBER][LENGTH];
//------------------------Function Definitions. -----------------------------------------
void printarr();
//------------------------Printarr -- Array printing function. --------------------------
void printarr()
{
int i,j;
printf("\n");
printf("Weight \t Value \t Object \n");
for(i=0;i<4;i++){
printf("%d \t %d \t %s \n", weight[i], value[i], &object[i][0]);
}
}
//------------------------Main. ---------------------------------------------------------
int main(int argc, char **argv)
{
FILE *fp; //File pointer.
char buffer[BUFFER]; //Temporary storage
int result; //sscanf return value.
int capacity; //User input.
int i,j=0; //Loop counters.
//Command Line Argument Parsing: Assigns input value to capacity.
if (argc != 2){
printf("Usage: %s number. Max 1024. \n",argv[0]); //Usage: *program* *num*
return(1);
}
if (1 != sscanf(argv[1],"%d",&capacity)){
printf("Usage: %s number. Max 1024. \n",argv[0]);
return(1);
}
//File reading.
fp=fopen("knapsack.data","r");
if(NULL==fp){
printf("Error opening file. \n");
exit(0);
}
//Write to arrays.
while(NULL != fgets(buffer, BUFFER, fp)){
result=sscanf(buffer, "%d %d %s", &weight[i], &value[i], &object[i][0]);
i++;
}
//Print the arrays.
printarr();
fclose(fp);
}
根据 GDB,当它遇到 sscanf 语句时会出现段错误。但据我所知,我访问这些位置的方式没有任何问题……显然我错了。任何帮助,将不胜感激。
【问题讨论】:
-
显示
knapsack.data。怀疑它比预期的多一个sscanf()。请注意,while循环不限制 i 0 到 127。i未初始化,也未测试。 -
是的,我打算写 inti,j;其次是i = j = 0;,我只是忘记了第二行。谢谢大家。