I have written a small program to convert vowels in a word to 'leet', for an assignment for the Harvard CS50 course I'm taking online. NB: this is relevant because we are using CS50 headers which give us access to a string data type. I'm not a student at Harvard, just taking the free version through edx.org.
My main function runs an if-else to validate the input, and then call the converter function if input is correct. In the else block, a string variable is assigned the value returned from my replace() function, and then the variable is (supposed to be) printed. Main will then return 0 and exit.
Problem: when I run this program, the leeted variable is purged when the printf statement is called in main. When I run our course debugger, I can see that the leeted variable is correctly assigned, but the second the debugger runs the printf line in main, the variable becomes empty. I'm absolutely baffled.
I have added another printf line at the end of the replace() function. When this print statement is commented out, the above problem occurs as described. However, when I activate the print statement at the end of the replace() function, the print statement in main() works.
Can anyone tell me why is is happening?
code:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
// function declarations
bool argcheck (int argc, string argv[]);
string replace(string input);
// #######################################
// MAIN
int main(int argc, string argv[])
{
if (argcheck(argc, argv) == false)
{
return 1;
}
else
{
string leeted = replace(argv[1]);
printf("from main(): %s\n", leeted);
}
return 0;
}
// #######################################
// FUNCTIONS
// input validation
bool argcheck (int argc, string argv[])
{
if (argc != 2)
{
printf("Usage: ./no-vowels word\n");
return false;
}
return true;
}
// converter implementation
string replace(string input)
{
char output[strlen(input)];
int i = 0;
while (input[i] != '\0')
{
switch(input[i])
{
case 'a':
output[i] = (char) '6';
break;
case 'e':
output[i] = (char) '3';
break;
case 'i':
output[i] = (char) '1';
break;
case 'o':
output[i] = (char) '0';
break;
default:
output[i] = input[i];
break;
}
i++;
}
string finished = (string) output;
// printf("from replace(): %s\n", finished);
return finished;
}