2015-02-05 199 views
-4

我該如何處理此代碼是通過將每個字母移動一定數量的字符來加密字符數組(如果數量爲2,則字符會被移動兩次 - 例如'a' - >'c')。變量大小的對象可能未被初始化,錯誤

我收到以下錯誤和警告。

Error on line 39: Variable Sized Object May not be initialized. 
Warning on line 39 : Unused Variable cyph 

代碼:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int CharToAlphaNumber (char letter) 
{ 
    int alpha; 
    int ascii=letter; 
    if (ascii >= 65 && ascii <=90) 
    { 
     alpha= ascii - 64; 
    } 
    else if (ascii >= 97 && ascii <= 122) 
    { 
     alpha= ascii - 96; 
    } 
    return alpha; 
} 


int main(int argc, char* argv[]) 
{ 
    if (argc != 2) 
    { 
     puts ("You need to enter a key, only one argument"); 
    } 
    else 
    { 
     int key = atoi(argv[1]); 
     puts ("Give me text:"); 
     char plaintext[100]; 
     scanf ("%s", plaintext); 
     printf ("You entered %s\n",plaintext); 

     char cyph[100]; 
     int i; 
     for (i=0;i<strlen(plaintext);i++) 
     { 
      char cyph[i]=(CharToAlphaNumber(plaintext[i])+key)%26; //Line 39 
     } 

     printf ("Cyphered:%s",cyph); 

    } 
    return 0; 
} 
+1

這將是很好,如果你可以在第39行添加評論說這是行39 – 2015-02-05 21:06:42

+3

'char cyph [i] =(CharToAlphaNumber(plaintext [i])+ key)%26;'在'for'循環的範圍內重新聲明一個新的'cyph',它獨立於聲明'char cyph [100] ;'在循環之外。刪除前面的「char」。 – lurker 2015-02-05 21:07:21

+0

請不要使用數字來表示字符。使用字符文字,例如「A」或「Z」。我沒有記住ASCII表中的十進制代碼,你的代碼很難閱讀和理解。 – 2015-02-05 21:14:31

回答

4

你有一個變量範圍的問題:

char cyph[100]; <--- cyph you intend to use 
    int i; 

    for (i=0;i<strlen(plaintext);i++) 
    { 
     char cyph[i]=(CharToAlphaNumber(plaintext[i])+key)%26; <--- new cyph 
    } 

裏面你for循環,你已經宣佈通過新的cyphchar cyph[i] = ...。您之前已宣佈cyphchar cyphy[100];,因此您無需再聲明它。更正:

char cyph[100]; 
    int i; 

    for (i = 0; i < strlen(plaintext); i++) 
    { 
     cyph[i] = (CharToAlphaNumber(plaintext[i]) + key) % 26; 
    } 
0

這裏有cyph表的第二個聲明:

char cyph[i]=(CharToAlphaNumber(plaintext[i])+key)%26;

此外:

  • strlen(plaintext)創建變量,將字符串的長度和條件使用。現在程序檢查長度每次循環輪

  • int ascii=letter;也沒有必要,您可以使用letter變量