I am getting some garbage values when declaring my array. I kinda understand that when declaring without initializing it provides garbage values, but I don't understand why the array is larger than what I set it to. The issue happens when I test with
./vigenere a
plaintext: a
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#define ABC 26 // sets the alphabet length
// Function to ensure input is a string
bool alpha_check(string text)
{
for (int i = 0, n = strlen(text); i < n; i++)
{
if (!isalpha(text[i]))
{
return false;
}
}
return true;
}
// Main function
int main(int argc, string argv[])
{
// Ensures single command-line argument and string
string k = argv[1];
if (argc != 2 || alpha_check(k) == false)
{
printf("Usage: ./vigenere k\n");
return 1;
}
string plain = get_string("plaintext: ");
int len_plain = strlen(plain);
int len_k = strlen(k);
//printf("%i\n", len_plain);
char cipher[len_plain];
//eprintf("%s\n", cipher);
// Turn plaintext into ciphertext
int c = 0; // Counter for each use of key
int h; // Index key
int key;
for (int i = 0; i < len_plain; i++)
{
h = c % len_k;
key = (isupper(k[h])) ? k[h] - 'A' : k[h] - 'a';
if (isalpha(plain[i]) && isupper(plain[i])) // Upper letter
{
cipher[i] = (plain[i] - 'A' + key) % ABC + 'A';
c++;
}
else if (isalpha(plain[i]) && islower(plain[i])) // Lower letter
{
cipher[i] = (plain[i] - 'a' + key) % ABC + 'a';
c++;
}
else
{
cipher[i] = plain[i];
}
}
printf("ciphertext: %s\n", cipher);
return 0;
}
When I use debug50 to run through the code, it seems that the cipher array is larger than it's supposed to be. len_plain = 1, so cipher should be 1 element, but it seems to not be the case.
Also I don't understand why if I 'uncomment' line 34, the printf before char cipher[len_plain], then it doesn't give me the issue. The same applies if I remove the function I have before the main function.