2012-10-08 63 views
0

在我的學校任務中​​,我必須用蠻力算法找到一個字符串。使用strcat的錯誤

如果長度是,例如,3這些是所有可能的組合: 一個 b Ç AA BA CA AB BB CB 交流 BC 立方厘米 AAA BAA CAA aba bba cba aca bca cca aab BAB 駕駛室 ABB BBB CBB ACB BCB 建行 AAC BAC CAC ABC BBC 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

*「爲什麼不是strcat工作?」是一個相當模糊的陳述。請說明您遇到的確切錯誤和行爲。 – Zeta

+0

@Zeta對不起。程序崩潰。分割錯誤 – Favolas

回答

2

您正在聲明pass變量,但您並未初始化它。當你勉強達成目標時,你首先假定它的結束是它的開始,但你需要做到這一點。

更重要的是,看看你的temp變量。你已經聲明它是一個char *,但你已經初始化它爲char(而不是指向一個char),然後在strcat()中你再次把它當作一個指針 - 但它並不指向任何有效的地方你的崩潰)。

+0

謝謝,但即使在初始化我收到分段錯誤 – Favolas

1

strcat期望以空字符結尾的字符串,但char pass[50]尚未初始化。設置pass[0] = '\0'以獲取有效的C字符串。

+0

謝謝。好吧,但通過炭字[50];傳遞[0] ='\ 0';仍然收到錯誤 – Favolas