I need to get strings dynamically but as I need to get more than one string, I need to use functions. So far I wrote this (I put //**** at places i think might be wrong)
char* getstring(char *str);
int main() {
char *str;
strcpy(str,getstring(str));//*****
printf("\nString: %s", str);
return 0;
}
char* getstring(char str[]){//*****
//this part is copy paste from my teacher lol
char c;
int i = 0, j = 1;
str = (char*) malloc (sizeof(char));
printf("Input String:\n ");
while (c != '\n') {//as long as c is not "enter" copy to str
c = getc(stdin);
str = (char*)realloc(str, j * sizeof(char));
str[i] = c;
i++;
j++;
}
str[i] = '\0';//null at the end
printf("\nString: %s", str);
return str;//******
}
printf
in the function is working but not back in main
function.
I tried returning void
, getting rid of *s
or adding, making another str2
and tring to strcpy
there or not using strcpy
at all. Nothing seems to working. Am I misssing something? Or maybe this is not possible at all
//Thank you so much for your answers