Chinaunix首页 | 论坛 | 博客
  • 博客访问: 532765
  • 博文数量: 150
  • 博客积分: 5010
  • 博客等级: 大校
  • 技术积分: 1861
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-17 00:19
文章分类

全部博文(150)

文章存档

2011年(1)

2009年(14)

2008年(135)

我的朋友

分类: LINUX

2008-08-12 11:04:13

char * strtok ( char * str, const char * delimiters );


Split string into tokens

A sequence of calls to this function split str into tokens, which are sequences of contiguous characters separated by any of the characters that are part of delimiters.




On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of last token as the new starting location for scanning.
 a first call: ptr = strtok( str, " " );
In subsequent calls: ptr = strtok( NULL , " " );

/*************************************************
 * *
 * example of strtok() *
 * *
 * *
 * ************************************************/



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


int main()
{
     char str[] = "mao zhe dong";
     char *ptr;
     ptr = strtok( str, " " );
     puts( ptr );
     while( ptr != NULL )
     { printf( " The ptr pointer is at %d \n" , ptr-str+1 );
        ptr = strtok( NULL , " " );
        if(ptr != NULL) puts( ptr );//---------------
     }


      return 0;
}

输出:

mao
 The ptr pointer is at 1
zhe
 The ptr pointer is at 5
dong
 The ptr pointer is at 9



但语句:
if(ptr != NULL) puts( ptr );//---------------
中去掉
if(ptr != NULL)
则输出是:

mao
 The ptr pointer is at 1
zhe
 The ptr pointer is at 5
dong
 The ptr pointer is at 9
Segmentation fault (core dumped)


Segmentation fault (core dumped) 这一句不知为什么会出现,原因何在?



-------------
阅读(1024) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~