在我的学校作业中,我必须找到一个带有暴力算法的字符串。
如果长度为例如3,则这些都是可能的组合: 一个 b C AA BA CA AB BB CB AC 公元前 CC AAA 咩 CAA ABA BBA CBA ACA BCA CCA AAB BAB 出租车 ABB BBB CBB ACB BCB 建行 AAC BAC CAC ABC 英国广播公司 CBC ACC BCC CCC
我在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没有工作,我正在进行细分移植?
答案 0 :(得分:2)
您正在宣布您的pass
变量,但您没有初始化它。当你完成它的结束时,你假设最初它的结束是它的开始,但你需要做到这一点。
更重要的是,请查看您的temp
变量。您已将其声明为char *
,但您已将其初始化为char
(而不是指向字符),然后在strcat()
中将其视为指针再次 - 但它没有指向任何有效的地方(导致你的崩溃)。
答案 1 :(得分:1)
strcat
期待以空字符结尾的字符串,但char pass[50]
尚未初始化。设置pass[0] = '\0'
以获取有效的C字符串。