Fscanf Seg Fault

时间:2014-02-13 02:36:15

标签: c segmentation-fault scanf

我一直在使用此代码获取分段错误,我试图打印字典的前6个单词。我很确定我正在使用fscanf,但我不确定如何/为什么......

#define _XOPEN_SOURCE
#include <unistd.h>
#include <stdio.h>

int main(int argc, char* enc[])
{
    if (argc != 2)
    {  
        printf("Improper command-line arguments\n");
        return 1;
    }

    FILE *Dict;
    Dict = fopen("/usr/share/dict/words", "r");

    if (Dict == NULL)
    {
        printf("Could not open dictionary");
        exit(1);
    }

    char* full = enc[1];
    char* salt[2];

    for (int i=0; i<2; i++)
    {
        salt[i] = &full[i];
    }

    char* key[50];

    for (int i=0; i<6; i++)
    {
        fscanf(Dict, "%s", *key);
        printf("%s", *key);
    }   
}

1 个答案:

答案 0 :(得分:1)

C字符串是字符数组:char name[10]或指向char的指针(指向有效的内存范围):char* name

这里有一个包含50个字符(或字符串)指针的数组:

char* key[50];

for (int i=0; i<6; i++)
{
    fscanf(Dict, "%s", *key);
    printf("%s", *key);
}  

key可能是一个50个字符的C字符串缓冲区:

char key[50];

for (int i=0; i<6; i++)
{
    fscanf(Dict, "%s", key);
    printf("%s", key);
}