遇到关于strtok的一个问题,郁闷了好一会儿终于找到答案

本文深入解析了C库函数strtok的内部实现机制,通过对比使用指针形式和数组形式作为参数的区别,揭示了导致内存错误的原因,并详细解释了strtok函数的核心处理流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天用这个函数用的郁闷了好一会儿,就是因为字符串是用的test2指针形式,而没有用test1那样的数组形式!

下面是我在网上看到的:

int main() {

char test1[] = "feng,ke,wei";

char *test2 = "feng,ke,wei";

char *p; p = strtok(test1, ",");

while(p)

{   

printf("%s\n", p);   

p = strtok(NULL, ",");   

}

return 0;

}

运行结果:

feng

ke

wei

但如果用p = strtok(test2, ",")则会出现内存错误,这是为什么呢?是不是跟它里面那个静态变量有关呢? 我们来看看它的原码:

/***
*strtok.c - tokenize a string with given delimiters
*
*         Copyright (c) Microsoft Corporation. All rights reserved.
*
*Purpose:
*         defines strtok() - breaks string into series of token
*         via repeated calls.
*
*******************************************************************************/
#include <cruntime.h>
#include <string.h>
#ifdef _MT
#include <mtdll.h>
#endif  /* _MT */
/***
*char *strtok(string, control) - tokenize string with delimiter in control
*
*Purpose:
*         strtok considers the string to consist of a sequence of zero or more
*         text tokens separated by spans of one or more control chars. the first
*         call, with string specified, returns a pointer to the first char of the
*         first token, and will write a null char into string immediately
*         following the returned token. subsequent calls with zero for the first
*         argument (string) will work thru the string until no tokens remain. the
*         control string may be different from call to call. when no tokens remain
*         in string a NULL pointer is returned. remember the control chars with a
*         bit map, one bit per ascii char. the null char is always a control char.
*       //这里已经说得很详细了!!比MSDN都好! 
*Entry:
*         char *string - string to tokenize, or NULL to get next token
*         char *control - string of characters to use as delimiters
*
*Exit:
*         returns pointer to first token in string, or if string
*         was NULL, to next token
*         returns NULL when no more tokens remain.
*
*Uses:
*
*Exceptions:
*
*******************************************************************************/
char * __cdecl strtok (
          char * string,
          const char * control
          )
{
          unsigned char *str;
          const unsigned char *ctrl = control;
          unsigned char map[32];
          int count;
#ifdef _MT
          _ptiddata ptd = _getptd();
#else  /* _MT */
          static char *nextoken;                          //保存剩余子串的静态变量      
#endif  /* _MT */
          /* Clear control map */
          for (count = 0; count < 32; count++)
                  map[count] = 0;
          /* Set bits in delimiter table */
          do {
                  map[*ctrl >> 3] |= (1 << (*ctrl & 7));
          } while (*ctrl++);
          /* Initialize str. If string is NULL, set str to the saved
           * pointer (i.e., continue breaking tokens out of the string
           * from the last strtok call) */
          if (string)
                  str = string;                               //第一次调用函数所用到的原串          
else
#ifdef _MT
                  str = ptd->_token;
#else  /* _MT */
                str = nextoken;                        //将函数第一参数设置为NULL时调用的余串
#endif  /* _MT */
          /* Find beginning of token (skip over leading delimiters). Note that
           * there is no token iff this loop sets str to point to the terminal
           * null (*str == '\0') */
          while ( (map[*str >> 3] & (1 << (*str & 7))) && *str )
                  str++;
        string = str;                                    //此时的string返回余串的执行结果 
          /* Find the end of the token. If it is not the end of the string,
           * put a null there. */
//这里就是处理的核心了, 找到分隔符,并将其设置为'\0',当然'\0'也将保存在返回的串中
          for ( ; *str ; str++ )
                  if ( map[*str >> 3] & (1 << (*str & 7)) ) {
                        *str++ = '\0';                //这里就相当于修改了串的内容 
                          break;
                  }
          /* Update nextoken (or the corresponding field in the per-thread data
           * structure */
#ifdef _MT
          ptd->_token = str;
#else  /* _MT */
        nextoken = str;                   //将余串保存在静态变量中,以便下次调用
#endif  /* _MT */
          /* Determine if a token has been found. */
          if ( string == str )
                return NULL;
          else
                  return string;
<think>好的,用户让我举一个使用strtok的例子。首先,我需要回忆一下strtok函数的用法和注意事项。strtok是C语言中用来分割字符串的函数,它通过指定的分隔符将字符串拆分成多个子串。用户可能刚学习字符串处理,或者在实际开发中遇到了需要解析字符串的情况,比如处理CSV数据或者日志文件。 接下来,我需要确定用户的需求层次。他们可能不仅想知道一个简单的例子,还想了解函数的工作原理以及使用时需要注意的地方。比如,strtok会修改原始字符串,用NULL来继续分割剩下的部分,这些细节对于正确使用函数非常重要。 然后,我要考虑如何组织例子。应该选择一个常见且易懂的场景,比如分割逗号分隔的字符串。例如,"apple,banana,orange,grape",用逗号和空格作为分隔符。这样用户容易理解,并且能直观看到分割结果。 在代码示例中,需要展示初始调用和后续调用的区别,即第一次传字符串指针,之后传NULL。同时,要处理可能的分隔符连续出现或字符串开头结尾有分隔符的情况,比如使用循环来遍历所有分割后的子串。 还要注意安全性问题,比如strtok不是线程安全的,但在例子中可能不需要涉及,除非用户有高级需求。此外,提醒用户strtok会修改原始字符串,如果需要保留原字符串,应该先拷贝一份。 最后,总结strtok的优缺点,比如简单易用但存在局限性,可能引导用户了解其他替代方法如strsep或自行实现分割函数,但根据用户当前的问题,可能暂时不需要深入这些内容,保持例子的简洁和清晰。</think>以下是一个使用 `strtok` 函数分割字符串的示例,包含详细注释和实际场景说明: --- ### **示例代码** ```c #include <stdio.h> #include <string.h> int main() { char str[] = "apple,banana,orange,grape"; // 原始字符串(必须是可修改的数组) const char* delimiter = ", "; // 分隔符:逗号或空格 // 第一次调用:传入待分割字符串 char* token = strtok(str, delimiter); while (token != NULL) { printf("分割结果: %s\n", token); // 后续调用:传入 NULL 继续分割剩余部分 token = strtok(NULL, delimiter); } return 0; } ``` --- ### **输出结果** ``` 分割结果: apple 分割结果: banana 分割结果: orange 分割结果: grape ``` --- ### **关键点解析** #### 1. **函数原型** ```c char* strtok(char* str, const char* delimiter); ``` - **第一次调用**:传入待分割字符串地址。 - **后续调用**:传入 `NULL`,函数会从上次分割的位置继续查找。 #### 2. **分隔符规则** - 分隔符可以是多个字符(示例中 `", "` 表示逗号或空格)。 - 连续的分隔符会被合并处理(例如 `"a,,b"` 会被分割为 `"a"` 和 `"b"`)。 #### 3. **修改原始字符串** - `strtok` 会 **直接修改原始字符串**,将分隔符替换为 `'\0'`。 (示例中 `str` 必须是数组,而非字符串常量,否则会导致崩溃) --- ### **实际应用场景** #### 场景:解析 CSV 数据 假设需要处理如下格式的 CSV 行: ```c char data[] = "John,Doe,25,New York"; ``` 使用 `strtok` 分割后可以提取姓名、年龄和城市: ```c char* firstName = strtok(data, ","); // "John" char* lastName = strtok(NULL, ","); // "Doe" char* age = strtok(NULL, ","); // "25" char* city = strtok(NULL, ","); // "New York" ``` --- ### **注意事项** 1. **线程安全性** `strtok` 内部使用静态变量记录位置,**非线程安全**。多线程环境下需使用 `strtok_r`(POSIX 标准)。 2. **空子串处理** 若字符串以分隔符开头(如 `",apple"`),首次分割会得到空字符串。需额外判断: ```c if (token != NULL && token[0] != '\0') { // 有效内容 } ``` 3. **不可重入性** 不能在嵌套循环中使用 `strtok` 分割多个字符串(会破坏内部状态)。 --- ### **替代方案** - **`strsep`**:BSD 函数,更适合处理空字段(如 `"a,,b"` 返回 `"a"`, `""`, `"b"`)。 - **手动实现**:通过循环和 `strchr` 自行控制分割逻辑。 --- 通过这个例子,你可以快速掌握 `strtok` 的核心用法和典型应用场景!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值