ZeeK ZeeK - 4 months ago 37
C Question

Variable Sized Object May not be initialized, error

What I am to do with this code is encrypt a char array by shifting each letter by a set amount of characters (if amount is 2 then characters are shifted twice - e.g. 'a' -> 'c').

I am getting the following error and warning.

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


Code:

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

Answer

You have a variable scope issue:

    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
    }

Inside your for loop, you've declared a new cyph via, char cyph[i] = .... You've already declared cyph previously as char cyphy[100];, so you don't need to declare it again. Corrected:

    char cyph[100];
    int i;

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