我正在尝试编写一个程序来打印字母表中所有单词的集合。这主要是一个让我习惯 C 中的字符串和指针的测试。我已经确定了一个递归解决方案,但我似乎在 strcat 中使用指针时遇到了麻烦。有什么建议说明我为什么会在这里出现段错误吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DIM 26
void print (char *);
char alphabet[26] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
char word[26];
int main(void) {
*word = '\0';
print(word);
return EXIT_SUCCESS;
}
void print (char *word){
for (int i = 0; i < DIM; ++i){
strcat(word, alphabet[i]);
printf("%c\n", word);
print(*word);
}
}
最佳答案
我认为最深的概念问题是你没有基本案例。您正在构建一个无限递归树。
试试这个:
void print (char *word){
if (strlen(word)<5){
for (int i = 0; i < DIM; ++i){
strcat(word, alphabet[i]);
printf("%c\n", word);
print(*word);
}
}
}
使用 C 语言时还有其他一些小问题,好的编译器会发现这些问题。打开警告,不要忽略它们!
关于c - 用 C 打印字母表中所有单词的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16626132/