Problem passing (char *s) into a class

I'm following an example from the book C++ without fear and it seems to fail.

I have a class with a constructor that takes a string input (I've included the function as inline for ease here)

class Fraction{...
...

Fraction(char *s){
int n = 0;
int d = 1;
char *p1 = strtok(s, "/, ");
char *p2 = strtok(NULL, "/, ");
if (p1 != NULL)
n = atoi(p1);
if (p2 != NULL)
d = atoi(p2);
set(n, d);
}
...
}

Then later in the code when I initialise a new Fraction class using the following
Fraction f3 = "1/2";
the code crashes with "Debugger has exited due to signal 10 (SIGBUS)."

If you define char s[] = "1/2"; inside the class function (and change obviously change the input char *s to something else to avoid declaring it twice) the program works fine.

So I'm guessing there is something wrong when passing the "1/2" as char *s. Although using cout << s; inside the class function reproduces the correct value to the screen.

I'm a complete beginner and as I've copy and pasted this from the book it's got me pretty lost.

Thanks for your help, and it's on page 329 of the book in case anyone with the book wants to know.



Last edited on
"1/2" is a const char*, meaning that it's content's can't be modified. strtok tries to do that, hence the error. You could make a copy of s in Fraction with new/malloc and strcpy and work on that, or use C++ library <sstream> (functions strtok, atoi, malloc, strcpy, etc. come from C).
Thank-you very much hamsterman, I seem to have fixed it.
Just one more quick question if that's OK;

How did you know that it was a const char* and not just char*?

Is it just something I should commit to memory, or is there some sort of rule that I am unaware of?

Thanks again
Which printing do you have? (Mine is 9th and my page 329 does not have any fraction(char *s) def)
I suppose you'll have to memorize it.
Here's what the standard says (2.13.4)
1. <...> An ordinary string literal has type “array of n
const char” and static storage duration (3.7), where n is the size of the string as defined below, and is
initialized with the given characters. <...>
2. Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation defined.
The effect of attempting to modify a string literal is undefined.
Notice that literals are not generated when you need them. Instead they exist somewhere for the whole lifetime of the program.
Thanks again hamsterman!

eidge: I'm using the second edition ebook, it is numbered page 329, but adobe reader says 362 of 616.

Cheers again for the help
You probably should get a newer book. Because my edition is dated march 2009 and has some deprecated info. (Just one or two random things but I suspect yours must be a lot worse..)
Topic archived. No new replies allowed.