Modifying a string in a function in C | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Modifying a string in a function in C

I want to change a string in a function. My code is: void fillStr(char * string); int main() { ... char * str; ... fillStr(str); printf("%s", str); //the str doesn't contain what I want return 0; } void fillStr (char * string) { //A successful code with the malloc and the realloc callings for getcharing to the string. printf("%s", string); //outputs the string } Help me please to find out what I did wrong?

1st Feb 2020, 9:21 PM
Evgeniy Smelov
Evgeniy Smelov - avatar
4 Answers
+ 4
Evgeniy Smelov, I've played around with this until it worked: Seems you need double pointers. This is my demonstration (input 'Hello'): #include <stdio.h> #include <stdlib.h> void fillStr(char **string); int main() { char * str; fillStr(&str); printf("%s", str); free(str); return 0; } void fillStr (char ** string) { *string = (char*)malloc(6); for(int i=0; i<5; ++i) (*string)[i] = getchar(); (*string)[5] = '\0'; printf("%s", *string); }
2nd Feb 2020, 12:05 AM
HonFu
HonFu - avatar
+ 1
Martin, the fillStr's code successfully fills the string using the getchar() but it doesn't actually change the str. That's the question.
1st Feb 2020, 11:30 PM
Evgeniy Smelov
Evgeniy Smelov - avatar
+ 1
The function works fine and it's printf() outputs exactly what I want. It gets a pointer on a string and works with it. Otherwise there would be a memory allocation error. The question is why the actual content of the main's str pointer doesn't change?
1st Feb 2020, 11:54 PM
Evgeniy Smelov
Evgeniy Smelov - avatar
+ 1
Martin, (I don't know how to mention someone) yes but in the heap. So the HonFu's advice to use double pointer works fine. Thank you!
2nd Feb 2020, 12:31 AM
Evgeniy Smelov
Evgeniy Smelov - avatar