c - 段错误 - sscanf 到 C 中的数组

标签 c arrays scanf

我只需要多一双眼睛来帮助我找出这段代码出现段错误的原因。

//------------------------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 语句时会出现段错误。但据我所知,我访问这些位置的方式没有任何问题……显然我错了。任何帮助,将不胜感激。

最佳答案

编辑:我只对了一半,修正这一行:

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 会在未初始化的情况下将 int 初始化为零,请自己尝试看看)。

编辑:忽略否决票,我是对的,但我确实在忘记删除第二个索引时犯了一个错误,您可以使用 object[i] 或 &object[i][0] 访问 c 字符串二维数组,两者都有效。 object[i] 用于访问整个字符串在我看来比使用 &object[i][0] 更清晰。

关于c - 段错误 - sscanf 到 C 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22161392/

相关文章:

c - 为什么当我试图获得 60 时 FPS 显示 30?

c - 如何更改 C 中的加载程序

c - c中scanf 3次不起作用?

c++ - 结束字符 `\0`算一个字符还是两个字符?

c - 为什么 scanf 需要两个数字?

c - 在 C 中通过 union 指针进行类型双关是否合法?

c - 从输入中读取整数并做出相应 react 的 Switch 语句

javascript - 使用 Moment.js 的日期数组

c++ - 交换数组

c - 在C中将数字保存在数组中