Using pointers returned by a function

This might be a noob question, but I cannot for the life of me find the answer on google.

I use the function strtok() to cut a string into pieces.
I then need to parse that string to an int using strtol().

If I do that as follow then everything works fine

int i;
char *p;
p = strtok( TEMPS, " " );
i = strtol( p, NULL, 10 );

But I don’t want to create a variable just to store an “in between” value. Here is where I get stuck. I tried using

int i;
i = strtol( strtok( TEMPS, " " ), NULL, 10  );

This doesn’t seem to work (segmentation fault) and I can’t figure why or how to otherwise do this without using a “in between” variable. TEMPS is a predefined string given by Coding game which contains numbers seperated by whitespace (the temperatures challenge). I’ve already completed the challenge, but I’m trying my hand at some code golfing. (That is the correct term right)

These 2 fragments of code are both fine, but your code is obviously something different because none of them actually parse a list of numbers. By the way and even if a cartesian approach is fine, the strtol function is a bit more powerful than you think and can save you the use of strtok.

2 Likes

Thanks Florent for your comment. You pointed me in the right direction. I know my code above doesn’t parse a list of number, but you are not allowed to discuss challenges so I’m not posting the entire code as that would be a solution to the challenge.

I figured out what was happening. It had something to do with using pointers. That stuff is not easy!