I have this code:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
string increment_str();
int main() {
string s = increment_str("xyz");
printf("String: %s\n", s);
}
//Increment the characters of a string through lowercase and then uppercase alphabet
string increment_str(string s)
{
int len = strlen(s);
// Initialize an r var to make sure s_return has enough space in memory
char r[len];
string s_ret = r;
//Remove the last character so the incremented one can be concatenated later
strcpy(s_ret, s);
s_ret[len - 1] = '\0';
switch (s[len - 1])
{
//At the end of lowercase alphabet start over at uppercase
case 'z':
strcat(s_ret, "A");
return s_ret;
break;
case 'Z':
//If all the the first character is the last letter start over with an extra character
if (len == 1)
{
strcpy(s_ret, "aa");
}
//Else refer to itself to increment the previous character in string
else
{
strcpy(s_ret, increment_str(s_ret));
strcat(s_ret, "a");
return s_ret;
}
//Needs brackets because you can't declare a var after a case
default:
{
//Concatenates the increased character with the string before it
char c[2] = {s[len - 1] + 1, '\0'};
strcat(s_ret, c);
return s_ret;
}
}
}
That should run normally, and it does in fact, except when it gets to the part of printing. Through debug50
I can see step by step how everything is going but when it tries to print s
it always prints "U" if run through debug50
or other garbage if run normally as seen in the screenshots bellow:
I am really not sure why this is happening or how to solve it so any help would be appreciated :)