With this you don't need to worry about holding reference to trim function return. You can have a static char buffer in the trim function and operate on it. Yes you can, but you cannot allocate new memory in the trim function as you will not be holding the return memory. When i print only string, it will print original string Well, like if I print trim(string) it will print trimmed string and ¯\_(ツ)_/¯Īlso, is there any way where I don't have to charge original string as While function pointers have their uses, this is a bit silly. Ta da! One variable, the original is left unmodified, no memory leaks. pass the trimmed string into the user function.
![i am da one god name copy and paste i am da one god name copy and paste](http://4.bp.blogspot.com/_u8oqCBwSreY/SUKPFTEGw3I/AAAAAAAAA34/U5xqvT0-AWY/w1200-h630-p-k-no-nu/Picture+001.jpg)
strncpy does not add a null byte, add it ourselves. Shrink the length to the last non-space char. Advance the pointer to the first non-space char Void trim(char *string, void(*func)(char *) ) You can get around this by passing a function pointer into trim and having trim manage all the memory for you.
#I AM DA ONE GOD NAME COPY AND PASTE FREE#
That means a new variable to hold the pointer so you can free it. If you don't want to modify the original string, that means you need to allocate memory for the modified string. The advantage is you have the option of duplicating the string if you want to retain the original. is there any way where i don't have to charge original string as well, like if i do trim(string) it will print trimmed string and when i print only string, it will print original string – avinashse 8 mins ago I believe above print can create dangling pointer situation.Īlso, is there any way where I don't have to charge original string as well, like if I print trim(string) it will print trimmed string and when i print only string, it will print original string Is there any way to do somthing like below where I dont need any second variable to print the trimmed string.
![i am da one god name copy and paste i am da one god name copy and paste](https://i.ytimg.com/vi/nSQVqSZQwxY/maxresdefault.jpg)
As the structure contains around 100 variables.
#I AM DA ONE GOD NAME COPY AND PASTE CODE#
Strncpy(trimmedStr,string+stPos,endPos+1) Ībove code is working fine, but i don't want to declare new variable that stores the trimmed word. char *trim(char *string)įor(stPos=0 stPos=0 & string=' ' -endPos) Ĭhar *trimmedStr = (char*)malloc(len*sizeof(char)) There is a structure which contains all string values, the structure is getting populated from the data coming from a file which contains spaces before and after the beginning of a word.