how to get char array position from token

When I run this code and break it on the last line, I want to see position to which the pointer "token" points to. How to do it?

1
2
3
4
char str[128] = "gaussian;gaussian1;gaussian2";
const char s[2] = ";";
char *token;
token = strtok(str, s);


http://oi59.tinypic.com/2mqkcy0.jpg
Last edited on
If you want to see, what the pointer actually points to, then you should dreference it, like so:
*token
If you want an position in your string (so 0, 1, 2, 3, str.size()-1), try something similar to this:
1
2
3
char *front = &str[0];    // points to first char in string
char *third = &str[2];    // points to third char in string
int pos = third - front;

TY, your example code works, but my code does something unexpected:
1
2
3
4
5
6
7
8
    char str[128] = "gaussian;gaussian1;gaussian2";
    const char s[2] = ";";
    char *token;
    int len;
    token = strtok(str, s);
    len = strlen(token);
    int pos2 = token; // warning*
    int pos = len - pos2;

http://oi61.tinypic.com/2qdwmqa.jpg

I would expect to get pos result either 0 or 7 or 8, am not sure. This is first call of strtok. In the case of second call token = strtok(NULL, s); how to get current position in the string str? The values which I want to work with are begin of the word and end of the word.

Also I got *warning:
initialization makes integer from pointer without a cast [enabled by default]|
Last edited on
Do you know, that is is C, not C++?
Also, you are not doing what I did in my example. len is not a pointer, but size_t containing the length of a string without the terminating null byte. So, what do you expect the value to be, which is produced by subtracting a memory address cast to int from an unsigned integer? I sure have no clue. Why don't you just tell us, what you are trying to achieve. Nobody wants to guess what your code is supposed to do.
Here is a little extended code, I hope you can use it to achieve what you want:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
	
    char str[] = "gaussian;gaussian1;gaussian2";
    const char delim[] = ";";
    char *token;
    char *first;
    int pos;

    token = strtok(str, delim);
    first = &str[0];

    while(token != NULL) {
        pos = token - first;
        printf("Current position: %d\n", pos);
        printf("Current token: %s\n\n", token);
        token = strtok(NULL, delim);
    }


Last edited on
Topic archived. No new replies allowed.