【发布时间】:2020-02-29 17:50:47
【问题描述】:
我是 C 的初学者,在 python 和 java 方面有一些经验。我想用C解决一个问题。问题是这样的:
将输入作为一个句子,单词之间只用空格隔开(只假设小写),按照以下规则改写句子:
1) 如果一个词是第一次出现,保持不变。
2) 如果单词出现两次,用被复制两次的单词替换第二次出现的单词(例如 two --> twotwo)。
3) 如果单词出现 3 次或更多,则删除第二次之后的所有出现。
将输出打印为一个句子。输入句子和每个单词的最大长度为 500 个字符和 50 个字符。
示例输入:jingle bells jingle bells jingle all the way
示例输出:jingle bells jinglejingle bellsbells all the way
我采取的方法是:
1) 读取输入,分离每个单词并将它们放入一个 char 指针数组中。
2) 使用嵌套的 for 循环遍历数组。对于第一个单词之后的每个单词:
A - If there is no word before it that is equal to it, nothing happens.
B - If there is already one word before it that is equal to it, change the word as its "doubled form".
C - If there is already a "doubled form" of itself that exists before it, delete the word (set the element to NULL.
3) 打印修改后的数组。
我对这种方法的正确性相当有信心。但是,当我实际编写代码时:
'''
int main()
{
char input[500];
char *output[500];
// Gets the input
printf("Enter a string: ");
gets(input);
// Gets the first token, put it in the array
char *token = strtok(input, " ");
output[0] = token;
// Keeps getting tokens and filling the array, untill no blank space is found
int i = 1;
while (token != NULL) {
token = strtok(NULL, " ");
output[i] = token;
i++;
}
// Processes the array, starting from the second element
int j, k;
char *doubled;
for (j = 1; j < 500; j++) {
strcpy(doubled, output[j]);
strcat(doubled, doubled); // Create the "doubled form"
for (k = 0; k < j; k++) {
if (strcmp(output[k], output[j]) == 0) { // Situation B
output[j] = doubled;
}
if (strcmp(output[k], doubled) == 0) { // Situation C
output[j] = ' ';
}
}
}
// Convert the array to a string
char *result = output[0]; // Initialize a string with the first element in the array
int l;
char *blank_space = " "; // The blank spaces that need to be addded into the sentence
for (l = 1; l < 500; l++) {
if (output[l] != '\0'){ // If there is a word that exists at the given index, add it
strcat(result, blank_space);
strcat(result, output[l]);
}
else { // If reaches the end of the sentence
break;
}
}
// Prints out the result string
printf("%s", result);
return 0;
}
'''
我对每个单独的块进行了一系列测试。有几个问题:
1)在处理数组时,循环中的strcmp、strcat、strcpy似乎都会给出Segmentation fault错误报告。
2) 打印数组时,单词没有显示它们应该执行的顺序。
我现在很沮丧,因为问题似乎都来自我的代码的一些内部结构缺陷,它们与我不太熟悉的 C 的内存机制非常相关。我应该如何解决这个问题?
【问题讨论】:
-
至于您的问题,您确实需要退后几步,回到您的书籍、教程或课程中,阅读更多关于指针的信息。指针必须指向某个有效的位置,您才能使用它!您有许多未初始化(因此是不确定的)指针。
-
是的,我在尝试运行程序时收到了这个警告,但是使用gets实际上是这个问题的要求之一,所以我认为无论如何我都应该遵循它。
-
那么给你这个作业或练习的书或教程应该扔掉!如果是老师,你需要告诉他或她。除非这是关于缓冲区溢出及其危险的练习,否则永远不要使用
gets,即使老师告诉你这样做。 -
使用
-Wall -Wextra编译。他们会告诉你doubled有什么问题
标签: c arrays algorithm segmentation-fault