简体   繁体   中英

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.

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.

你想获得的第一个字节的字符pch -没有地址pch

ctext[mlen] = *pch;
#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM