Question

I have the following code:

    char buffer[50];
    char * tok, tok2;
    buffer = "addition 1 2";
    tok = strtok(buffer, " ");
    // get the second token
    tok = strtok(NULL, " ");
    tok2 = tok;
    // get the last token
    tok = strtok(NULL, " ");
    // pass them to the function
    foo(atoi(tok2), atoi(tok));

However, I got segmentation fault 11. What I wanted to do is to store the second value (integer 1) and the last value (integer 2) and pass them to foo(int a, int b). How could I do this?

Was it helpful?

Solution

char * tok, tok2;

The above statement defines tok to be of type char * and tok2 of type char. It's equivalent to

char *tok;
char tok2;

char * is not a new type. You should always associate * with the variable, not the type. You should change that statement to

char *tok, *tok2;

You cannot assign arrays in C. Therefore the following statement is wrong -

buffer = "addition 1 2";

What you should do is to initialize the array buffer with the string literal -

char buffer[] = "addition 1 2";

Also, note that the function strtok modifies its first argument. Its signature is

char *strtok(char *str, const char *delim);

It's for this reason that the first parameter str is not const qualified unlike the second one delim.

OTHER TIPS

You cannot assign a string literal to buffer since it is a char array, not a char* (how did this even compile??).

If you make buffer a char*, then the assignment will work, but strtok will try writing its NUL terminators directly into the string literal, which is probably in a read-only region of memory.

Instead, you should use strcpy(buffer, "addition 1 2"); to copy the read-only string into your read-write buffer.

And also what @ajay said... You should really pay attention to compiler warnings about type mismatches!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top