franka
franka

Reputation: 1917

How can I fix this strtok() call

I have a problem with strtok() - it does not return the input as expected.

void parse_input(const char *input,unsigned char *ctext, int mlen){
  char * str = strdup(input);
  char * pch = strtok(str,"-");

  while (pch != NULL)
  {

    ctext[mlen] = (int) pch;


    pch = strtok (NULL, "-");

    mlen++;

  }

On input like 1-2-3-4 I would want it to fill ctext with [1,2,3,4]. That doesn't work, however. What am I doing wrong? Any help appreciated.

Upvotes: 1

Views: 221

Answers (3)

BLUEPIXY
BLUEPIXY

Reputation: 40145

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void parse_input(const char *input,unsigned char *ctext[], int *mlen){
    char * str = strdup(input);
    char * pch = strtok(str,"-");

    while (pch != NULL){
        ctext[(*mlen)++] = (unsigned char*)pch;
        pch = strtok (NULL, "-");
    }
}

int main(void){
    unsigned char *ctext[16];
    int mlen=0;
    int i;

    parse_input("1-2-3-4", ctext, &mlen);
    printf("[ ");
    for(i=0;i<mlen;++i){
        printf("%s", ctext[i]);
        if(i<mlen -1)
            printf(", ");
    }
    printf(" ]\n");
    //free(ctext[0]);
    return 0;
}

Upvotes: 0

user529758
user529758

Reputation:

ctext[mlen] = (int) pch;

That stores the numeric value of the pointer, whereas you really want the character pointed to by the pointer. Time to read a good article/book/tutorial on pointers.

ctext[mlen] = *pch;

is what you're looking for.

Upvotes: 3

K Scott Piel
K Scott Piel

Reputation: 4380

You want to get the character in the first byte of pch -- not the address of pch

ctext[mlen] = *pch;

Upvotes: 1

Related Questions