2017-07-11 47 views
0

我正在用C編寫一個程序來查找ceaser密碼中的轉換。作爲這部分的一部分,我首先執行每一個可能的移動,0-26,在解密的消息上,我使用一個結構來存儲移位和消息。爲此,我已經將結構作爲指針傳遞給函數。但是,當我嘗試將結構的消息成員更改爲解密的消息時,我得到以下錯誤:行'strcpy(s-> message,cipherText)'上的' - >'(有'int')的無效類型參數; 」。c-在函數中分配結構成員時出錯

在函數中,我也將一個局部變量分配給一個結構成員,這工作正常。

代碼:

#include <stdio.h> 
#include <string.h> 
#define ENCRYPT 0 
#define DECRYPT 1 

struct Solution { 
    int key; 
    char message[]; 
}; 

void Ceaser(struct Solution *s, char cipherText[], int mode); 

void main(){ 
    struct Solution solutions[26]; 
    char cipherText[] = "lipps, asvph."; 

    for (int i = 0; i <= 26; ++i) { 
     solutions[i].key = i; 
     Ceaser(&solutions[i], cipherText, DECRYPT); 
     printf("Key: %d\tPlain text: %s\n", solutions[i].key, 
     solutions[i].message); 
    } 
} 

void Ceaser(struct Solution *s, char cipherText[], int mode) { 

    int len = strlen(cipherText); 
    int c; 
    int key = s->key; 

    for (int s = 0; s <= 26; ++s) { 
     if (mode == DECRYPT) { 
      key *= -1; 
     } 

     for (int i = 0; i < len; ++i) { 
      c = cipherText[i]; 

      if (c >= 'A' && c <= 'Z') { 
       cipherText[i] = 'A' + ((c + key - 'A') % 26);   
      } else if (c >= 'a' && c <= 'z') { 
       cipherText[i] = 'a' + ((c + key - 'a') % 26);   
      } 
     } 
    //Error occurs below 
    strcpy(s->message, cipherText); 
    } 
} 
+1

's-> message':'char message [];'沒有空格。 – BLUEPIXY

+2

問題是你有兩個名爲s的變量。內部int會隱藏外部Solution * s。如果你使用gcc,-Wshadow標誌可以很好地找到像這樣的問題。 –

+0

@BjornA。謝謝我,雖然這將是簡單的事情,我不敢相信我沒有注意到衝突。感謝編譯器提示。 – Henry

回答

0

的問題是,你沒有正確關閉for(int s=...和編譯器認爲,通過s->你是指循環變量s而不是Solution* s功能參數。

這就是爲什麼你會得到那個無效類型錯誤。

以下是固定的(更好的縮進)版本:

void Ceaser(struct Solution *s, char cipherText[], int mode) { 
    int len = strlen(cipherText); 
    int c; 
    int key = s->key; 

    for (int s = 0; s <= 26; ++s) { 
    if (mode == DECRYPT) { 
     key *= -1; 
    } 

    for (int i = 0; i < len; ++i) { 
     c = cipherText[i]; 

     if (c >= 'A' && c <= 'Z') { 
     cipherText[i] = 'A' + ((c + key - 'A') % 26); 
     } else if (c >= 'a' && c <= 'z') { 
     cipherText[i] = 'a' + ((c + key - 'a') % 26); 
     } 
    } 
    } //<--------was missing 

    strcpy(s->message, cipherText); 
} 

如果你讓編譯器警告-Wshadow工作你得到的是非常豐富的。

g++ 
test.cpp:65:30: note: shadowed declaration is here 
void Ceaser(struct Solution *s, char cipherText[], int mode) { 

clang++ 
note: previous declaration is here 
void Ceaser(struct Solution *s, char cipherText[], int mode) { 


icpc 
warning #1599: declaration hides parameter "s" (declared at line 65) 
    for (int s = 0; s <= 26; ++s) { 
0
void Ceaser(struct Solution *s, char cipherText[], int mode){ 
.... 
for (int s = 0; s <= 26; ++s){ 

你能不能看到明顯的衝突在這裏 - 您使用的是相同的變量名的兩倍。 int s將覆蓋for循環的範圍s的先前聲明,因此您的代碼將無法與先前聲明的代碼進行交互。

將第一個s更改爲適當的變量名稱(即「解決方案」),以避免衝突,同時也很明顯變量的目的是什麼。單字符變量並不是非常清楚它們的用途,即使它們僅用於循環。