我正试图编写一个程序,打印字母表中所有单词的集合。这主要是一个测试,让我习惯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 = ' ';
print(word);
return EXIT_SUCCESS;
}
void print (char *word){
for (int i = 0; i < DIM; ++i){
strcat(word, alphabet[i]);
printf("%cn", word);
print(*word);
}
}
我认为最深刻的概念问题是你没有基本情况。你正在构建一个无限递归树。
试试这个:
void print (char *word){
if (strlen(word)<5){
for (int i = 0; i < DIM; ++i){
strcat(word, alphabet[i]);
printf("%cn", word);
print(*word);
}
}
}
在使用C语言时,还有其他一些小问题,好的编译器会发现的。打开警告,不要忽视它们!
-
strcat
的第二个参数是字符串。所以你需要发送achar
的空终止数组。 -
printf
的%c
格式 表示
int
,但word
是指向char
的指针。您需要word长度为27字节,并将最后一个字节设置为零。
否则printf会溢出到你不拥有的内存中;Printf只在字节值为0时终止。
你的print函数也无限地调用自己。这将很快导致堆栈溢出。
因为1。您的缓冲区太短(对于26个字母和结束的0,您需要27字节);strcat()
需要字符串,你给它输入char
和3。你的函数有无限递归,它永远不会终止。
虚拟迭代替换解:所有子集=随重复变化,存在2 ^ n
子集:
char abc[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'
};
for (long i = 0; i < (1 << 26); i++) {
for (int j = 0; j < 26; j++) {
if ((i >> j) & 1) {
fputc(abc[j], stdout);
}
}
fputc('n', stdout);
}
不客气。