1 #include<stdio.h>
2 #include<string.h>
3 int main()
4 {
5 char *source="zhang.yong,29";
6 char *des[3];
7 printf("%lu\n%s\n",sizeof(source),source);
8 char *buf=source;
9 int i=0;
10 printf("fff\n");
11 des[0]=strtok(source,".");
12 printf("ggg\n");
13 printf("%s\n",des[0]);
14 des[1]=strtok(NULL,",");
15 printf("%s\n",des[1]);
16 printf("%s\n",source);
17 printf("%lu\n",sizeof(source));
18 return 0;
2 #include<string.h>
3 int main()
4 {
5 char *source="zhang.yong,29";
6 char *des[3];
7 printf("%lu\n%s\n",sizeof(source),source);
8 char *buf=source;
9 int i=0;
10 printf("fff\n");
11 des[0]=strtok(source,".");
12 printf("ggg\n");
13 printf("%s\n",des[0]);
14 des[1]=strtok(NULL,",");
15 printf("%s\n",des[1]);
16 printf("%s\n",source);
17 printf("%lu\n",sizeof(source));
18 return 0;
19 }
strtok是针对字符串的处理函数,源字符串source在定义为字符串的指针时,使用strtok函数会出现段错误,后续对字符串操作时,出现内存非法操作,需要定义成source[ ],函数的返回值为从指向被分割的子串的指针
strtok_r:
1 #include<stdio.h>
2 #include<string.h>
3 int main()
4 {
5 char source[]="zhang yong,23 56,male female";
6 char *buf;
7 char des[20];
8 char *unk;
9 unk=strtok_r(source,",",&buf);
10 printf("%s\n%s\n%s\n",source,buf,unk);
11 }
12
结果::
nfore@nfore:~/f/feifei $ gcc -o tok_c tok_r.c
nfore@nfore:~/f/feifei $ ./tok_c
zhang yong
23 56,male female
zhang yong
nfore@nfore:~/f/feifei $
URL:http://www.360doc.com/content/12/0423/15/4186481_205896599.shtml