2015-02-05 198 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变量