I am having trouble figuring out why I keep getting a segfault when trying to run a small test. The idea is that I send in a fraction as a string such as "1/4" in this case and the string_to_fraction is supposed to tokenize the string by getting rid of the "/" and setting the numerator value to 1 and the denominator value to 4 then returning it.
typedef struct {
int numer;
int denom;
}Fraction;
Fraction string_to_fraction(const char *S);
main(){
const char* strn = "1/4";
Fraction myFrac;
myFrac = string_to_fraction(strn);
return 0;
}
Fraction string_to_fraction(const char *S)
{
Fraction result = {0,1};
char *p;
char n[100] = {}, d[100] = {};
p = strtok(S,"/");
if(p == NULL){
printf("String of improper format");
return result;
}
strcpy(n,p);
p = strtok(NULL,"/");
strcpy(d,p);
result.numer = n;
result.denom = d;
return result;
}
the segfault occurs at the first instance of strtok, e.g. p = strtok(S,"/");
but I have no idea why this is happening, I have tried passing many different things into the string_to_fraction function but it always segfaults. Any insight is much appreciated as all the other issues people had with strtok causing a segfault did not really seem to pertain to my situation as far as I can tell.
edit: forgot to include my declaration to the fraction_to_string function on here, that is now fixed. I did it in my code but this code is split by a lot of junk so i just re-wrote a lot of it here.