我正在调试我的程序,我似乎无法找到任何答案。我的程序需要一个文件,将这些单词复制到一个动态数组中,并保留多个单词的字数。C中动态输入程序的问题
问题1)对于我编译的内容,我尝试了不同的输入示例。一个读“foo bar bat bam”和另一个“foo foo bar bam”。第一个输出是所有四个字的顺序,第二次打印
foo
bar
bam
foo bar bam
我想不通这是为什么。
问题2)我得到一个分段错误,当我尝试初始化新录入的单词数1线
arrayOfWords[unique_words].count = 1;
是给我分割故障。并且使用 - >不能编译。我不能动态增长数组。我现在评论他们,但你可以看到我的两个策略,试图扩大阵列。
我非常感谢您的帮助!
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INITIAL_SIZE 10
typedef unsigned int uint;
typedef struct { char * word; int count; } wordType;
int main(void)
{
wordType *arrayOfWords = (wordType*)malloc(1 * sizeof (wordType));
wordType *tempArray;
FILE * inputFile;
char temp[50];
uint i;
uint j;
uint unique_words;
uint exists;
uint wordAdded;
inputFile = fopen("input.txt", "r");
if(inputFile == NULL)
{
printf("Error: File could not be opened\n");
/*report failure*/
return 1;
}
i = 0;
unique_words = 0;
wordAdded = 0;
while(fscanf(inputFile, "%s", temp) != EOF)
{
/*if a word was added, then increase the size by one
if(wordAdded == 1)
{
tempArray = malloc((unique_words + 1) * sizeof(wordType));
memcpy(arrayOfWords, tempArray, unique_words + 1);
free(tempArray);
wordAdded = 0;
} */
/*
if(wordAdded == 1)
{
arrayOfWords = realloc(arrayOfWords, unique_words + 1);
wordAdded = 0;
}*/
exists = 0;
for(j = 0; j < unique_words; j++)
{
if(strcmp(arrayOfWords[j].word, temp) == 0)
{
arrayOfWords[j].count++;
exists = 1;
}
}
if(exists == 0)
{
arrayOfWords[unique_words].word = malloc(sizeof(char)
* (strlen(temp)+1));
strcpy(arrayOfWords[unique_words].word, temp);
/*arrayOfWords[unique_words].count = 1; */
unique_words++;
wordAdded = 1;
}
i++;
}
printf("unique_words = %d\n", unique_words);
for(i = 0; i < unique_words; i++)
printf("%s\n", arrayOfWords[i].word);
fclose(inputFile);
/* for(i = 0; i < size; i++)
free(arrayOfWords[0].word);*/
return 0;
}
感谢您的帮助,这澄清了很多。根据需要分配而不是初始化更有意义。 – Busch 2013-05-01 00:03:22
这对您的理解很有帮助。 – BLUEPIXY 2013-05-01 10:12:27