相同的字符串存储在数组

时间:2017-11-14 22:23:50

标签: c arrays string

我正在尝试将不同的字符串保存到char *数组中,但由于某种原因,它将相同的字符串保存到数组的每个元素中,即使我将不同的字符串存储到元素中。

char string[99];
char line[99];
FILE* out = fopen("data.out", "w");
char *words[999];
int wcount = 0;


 while(fscanf(fpointer, "%s", string) != EOF)
{
    if((strlen(string) + strlen(line))-1 <= number)
    {
        strcat(line, string);
        char word[99];
        strcpy(word, string);
        words[wcount] = word;
        printf("should have saved %s at %d\n", word, wcount);
        wcount++;

        if(strlen(line) < number)
        {
            strcat(line, " ");
        }
        puts(line);
    }
    else
    {
        fprintf(out,"%s", line);
        fprintf(out, "\n");
        strcpy(line, string);
        strcat(line, " ");
    }
}

fprintf(out, "%s", line);

printf("wcount is %d\n", wcount);
puts(words[0]);
puts(words[1]);
puts(words[2]);

以“应该已保存”开头的print语句打印出应该保存到单词数组中的正确字符串,但最后的print语句显示存储的最后一个单词位于数组的每个元素中。

1 个答案:

答案 0 :(得分:1)

也许你想要这样的东西? 现在无法测试。

 char **words = NULL;
 while(fscanf(fpointer, "%s", string) != EOF)
{
    if((strlen(string) + strlen(line))-1 <= number)
    {
        strcat(line, string);
        words = realloc(words,sizeof(char *)*(wcount+1));
        words[wcount] = malloc(sizeof(char)*(strlen(string)+1));
        strcpy(words[wcount], string);
        printf("should have saved %s at %d\n", words[wcount], wcount);
        wcount++;

        if(strlen(line) < number)
        {
            strcat(line, " ");
        }
        puts(line);
    }
    else
    {
        fprintf(out,"%s", line);
        fprintf(out, "\n");
        strcpy(line, string);
        strcat(line, " ");
    }
}

fprintf(out, "%s", line);

printf("wcount is %d\n", wcount);
puts(words[0]);
puts(words[1]);
puts(words[2]);