Segfault - sscanf到C中的数组

时间:2014-03-04 01:57:33

标签: c arrays scanf

我只需要一副额外的眼睛来帮助我找出为什么这段代码是segfaulting。

//------------------------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声明时会出现段错误。但据我所知,我访问这些地点的方式并没有错......显然我错了。任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:-2)

编辑:我是对的,修好这一行:

result=sscanf(buffer, "%d %d %s", &weight[i], &value[i], &object[i][0]);

看起来像这样:

result=sscanf(buffer, "%d %d %s", &weight[i], &value[i], object[i]);

您正在读取整个字符串,因此您需要写入c字符串位置,在本例中为object [i]。另外,init i是最佳实践(尽管如果未初始化,gcc会初始化为零,请自行尝试并查看)。

编辑:忽略downvote,我是正确的但我确实在忘记删除你的第二个索引时出错了,你可以使用object [i]或&amp; object [i] [0]访问ac string 2d数组,两者都是工作。用于访问整个字符串的object [i]看起来比使用&amp; object [i] [0]更清晰。