Im helping my friend in is HW and i got a weird blackout. I'm using a function which designated to "decrypt" a message from a given string, the process is working fine(i debugged that to check) but i forgot how to return the value from the function to the main program I have not touched in C lang for a while so im little blacked out here
Code(Edited):
void func(char* str, char* new_str, int i, int k) {
if (i < strlen(str)) {
if ((str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'A' && str[i] <= 'Z')) {
new_str[k] = str[i];
func(str, new_str, i + 1, k + 1);
}
else {
func(str, new_str, i + 1, k);
}
}
}
int main()
{
char str[100] = "l#e%i&n^&%a^&%D$%o#@T(r*e^^t*t(e%$L"; //Iterate from end to start.
char new_str[100] = ""; //Use k index here.
func(str, new_str, 0, 0);
printf("%s", new_str);
return 0;
}
You return a pointer (reference) to the first character of the string.
char* someFunction() {
char* newString = malloc( sizeof( char ) * 13 );
strncpy( newString, "hello world!", 12 );
newString[12] = '\0';
return newString;
}
If your string can't be modified (because it is hard-coded) return a const char*
const char* someFunction2() {
return "hello world!";
}
In both of these cases, the returned value is an address, pointing to a char. The C-convention of the first '\0'
character terminating the string is what is used to find the end of the string.
I would not make the function return anything at all
pass a pointer to it like this:
void func(char* str, char* new_str, int i, int k)
and then override new_str[] in the function. Also, remember that char[10] initializes an array of 10 chars, so if anything you must return a pointer char*, not a single char.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.