What Is My Mistake? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

What Is My Mistake?

I am taking a string and a char from user. for example: string=hey\ char=\ And I am trying to take the string before a specified character. In this case it is "\". But my program is not working. Probably I have mistakes at returning pointer from function. Could you say what is my mistake? https://code.sololearn.com/c761aBytQvGo/?ref=app

8th Dec 2017, 9:05 AM
Yusuf
Yusuf - avatar
5 Answers
+ 2
You keep incrementing the another pointer, so by the time you return it, it is no longer pointing to the beginning of the array. Instead you may want to use *(another+k) = *ptr; instead and remove the another++; You may also want to add a null terminator before you return another. You are doing the same thing with the array passed to the before function. When you return from it array is also no longer pointing to the beginning. You could do the same thing ( adding k to it ) as well. Lastly, unless you have a good reason to use void main, use int main instead :)
8th Dec 2017, 9:40 AM
Dennis
Dennis - avatar
+ 2
umm... There are a few issues with this code (not freeing memory when you are done etc). The first two to look at are inside the before function: You should put a null char on the end of the char array. You increment the another pointer as you go when copying each char to the array. This means you return the end address of the array instead of the beginning of the array. Therefore none of the string will print.
8th Dec 2017, 9:48 AM
Jared Bird
Jared Bird - avatar
+ 1
I don't know where to use void main or int main @Dennis. I am using void main because it is short.
8th Dec 2017, 1:07 PM
Yusuf
Yusuf - avatar
+ 1
@Joseph Hardrock You can either use int main(void) or int main(int argc, char **argv) but not void main as it's not standard C/C++
8th Dec 2017, 1:28 PM
Dennis
Dennis - avatar
+ 1
Thank you @Dennis
8th Dec 2017, 4:18 PM
Yusuf
Yusuf - avatar