[英]How can I fix this strtok() call
I have a problem with strtok() - it does not return the input as expected. 我有strtok()的问题 - 它没有按预期返回输入。
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]. 在像1-2-3-4
这样的输入上,我希望它用[1,2,3,4]填充ctext。 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.