在我的学校作业中,我必须使用强力算法找到一个字符串。
例如,如果长度为 3,则这些是所有可能的组合: A b C 一个 吧 加州 ab bb cb 交流电 公元前 抄送 啊啊 咩 CAA 阿巴 bba CBA 阿卡 bca cca aab 宝贝 出租车 abb bbb cbb 交流电 BCB build 银行 aac 背 cac 美国广播公司 英国广播公司 加拿大广播公司 acc 密件抄送 抄送
我在 strcat
中遇到问题。
这是代码。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
# define PASS_SIZE 3
char letters[] = "abc";
char test[] = "acb";
int count = 0;
int nbletters = sizeof(letters)-1;
int bruteForce(int size);
int main() {
int i = 0;
int notFound = 1;
for (i = 1; i <= PASS_SIZE && notFound == 1; i++){
notFound = bruteForce(i);
};
printf("Count: %d\n",count);
return -1;
}
int bruteForce(int size){
int i;
int entry[size];
char pass[50];
char *temp;
for(i=0 ; i<size ; i++){
entry[i] = 0;
}
do {
for(i=0 ; i<size ; i++){
temp = letters[entry[i]];
printf("%c", temp);
strcat(pass,temp); /*Getting error here*/
}
count++;
printf("\n");
/*Compare pass with test*/
if (strcmp (pass,test) == 0){
return 0;
};
for(i=0 ; i<size && ++entry[i] == nbletters; i++){
entry[i] = 0;
}
} while(i<size);
return 1;
}
可能暴力算法不是最好的。
为什么 strcat 不工作而且我遇到段错误?
最佳答案
您正在声明您的 pass
变量,但您并未对其进行初始化。当您连接到它的末尾时,您最初假设它的末尾就是它的开始,但您需要做到这一点。
更重要的是,查看您的 temp
变量。您已将其声明为 char *
,但已将其初始化为 char
(而不是指向 char),然后在 strcat()
你又把它当作一个指针来对待——但它没有指向任何有效的地方(导致你的崩溃)。
关于c - 使用 strcat 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12784650/