I am trying to figure out how to pass a string as a parameter and then return another String in C. I am practicing by simply adding test. This is for a project I am stuck on where I need to do some validation on a string and wanted to do it in a seperate function. Obviously my example is more complicated than it should be but I need to know how to manipulate a string that has been passed as a parameter then return it as another string.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void stringCopy(char *);
int main()
{
char delay;
char string[10];
printf("Enter the string: ");
scanf("%s", string);
char newString[20];
strcat(newString, stringCopy(string));
printf("String: %s", newString);
delay = getchar();
delay = getchar();
}
/*char stringCopy(char *str)
{
char string2[20] = "test";
strcat(string2, str);
return string2;
}*/
char* stringCopy(char *str)
{
char *string2 = malloc(sizeof(char)*20);
strcpy(string2,"test");
strcat(string2, str);
return string2;
}
Here is all my code for my little practice program thanks in advance for any help.
**edited to show changes. I just don't know how to access the new new (string2) in the main().
edit2: I just can't seem to get it. I really appreciate everyones help though. Really frustrating. I'm going to keep trying but I don't even understand why i'm getting the errors or how to access my new string in main().
edit3: im an idiot, I had the file extension as .cpp and not as .c.
char*variable. Then use it like any other string. Don't forget tofree()it.