简体   繁体   English

使用strcat时出错

[英]Error using strcat

On my school assignment i have to find a string with a brute force algorithm. 在我的学校作业中,我必须找到一个具有蛮力算法的字符串。

If the length is, for example , 3 these are all the possible combinations: abc aa ba ca ab bb cb ac bc cc aaa baa caa aba bba cba aca bca cca aab bab cab abb bbb cbb acb bcb ccb aac bac cac abc bbc cbc acc bcc ccc 例如,如果长度为3,则表示所有可能的组合:abc aa ba ca ab bb cb ac bc cc aaa baa caa aba bba cba aca bca cca aab bab cab abb abb bbb cbb acb bcb ccb aac bac cac abc abc bbc cbc acc密件抄送ccc

I having problems in strcat . 我在strcat中遇到问题。

here is the code. 这是代码。

#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;
}

Probably the brute force algorithm is not the best one. 蛮力算法可能不是最佳算法。

Why isn't strcat working and I'm getting segmentation foult? 为什么strcat无法正常工作,而我却无法进行细分?

You are declaring your pass variable but you are not initializing it. 您在声明您的pass变量,但没有对其进行初始化。 When you concatinate onto its end, you're assuming initially its end is its start, but you need to make that be the case. 当您强调它的结束时,您首先假设它的结束是它的开始,但是您需要确保情况如此。

More importantly, take a look at your temp variable. 更重要的是,请看一下您的temp变量。 You've declared it to be a char * , but you've initialized it to be a char (instead of pointing to a char), and then in strcat() you treat it like a pointer again -- but it's not pointing anywhere valid (causing your crash). 您已将其声明为char * ,但已将其初始化为char (而不是指向char),然后在strcat()再次将其视为指针-但它没有指向任何地方有效(导致崩溃)。

strcat is expecting a null-terminated string, but char pass[50] hasn't been initialized. strcat期望以null结尾的字符串,但是char pass[50]尚未初始化。 Set pass[0] = '\\0' to get a valid C string. 设置pass[0] = '\\0'以获得有效的C字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM