strtok 影响输入缓冲区 [英] strtok affects the input buffer

查看:43
本文介绍了strtok 影响输入缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 strtok 来标记字符串,strtok 会影响原始缓冲区吗?例如:

I am using strtok to tokenise the string, Is strtok affects the original buffer? For e.g:

   *char buf[] = "This Is Start Of life";
    char *pch = strtok(buf," "); 
    while(pch) 
    {
        printf("%s \n", pch);
        pch = strtok(NULL," "); 
    }*
    printf("Orignal Buffer:: %s ",buf);

Output is::
         This
         Is
         Start
         Of
         life
         Original Buffer:: This

我读到 strtok 返回指向下一个标记的指针,那么 buf 是如何受到影响的?有没有办法保留原始缓冲区(没有额外的复制开销)?

I read that strtok returns pointer to the next token, then how the buf is getting affected? Is there way to retain original buffer (without extra copy overhead)?

后续问题:: 从目前的答案来看,我想没有办法保留缓冲区.那么如果我使用动态数组创建原始缓冲区,如果strtok会影响它,那么在释放原始缓冲区时会出现内存泄漏还是strtok负责释放内存呢?

Follow-on Question:: from so far answers I guess there is no way to retain the buffer. So what if I use dynamic array to create original buffer and if strtok is going to affect it, then there will be memory leak while freeing the original buffer or is strtok takes care of freeing memory?

推荐答案

strtok() 不会创建新字符串并返回它;它返回一个指向您作为参数传递给 strtok() 的字符串中的标记的指针.因此原始字符串受到影响.

strtok() doesn't create a new string and return it; it returns a pointer to the token within the string you pass as argument to strtok(). Therefore the original string gets affected.

strtok() 破坏字符串意味着它将 delimiter 字符替换为 NULL 并返回指向该标记开头的指针.因此,在您运行 strtok() 后,delim 字符将被替换为 NULL 字符.您可以阅读 link1 link2.

strtok() breaks the string means it replaces the delimiter character with NULL and returns a pointer to the beginning of that token. Therefore after you run strtok() the delim characters will be replaced by NULL characters. You can read link1 link2.

正如您在 link2 示例的输出中所见,您得到的输出符合预期,因为 delim 字符被 strtok.

As you can see in output of example in link2, the output you are getting is as expected since the delim character is replaced by strtok.

这篇关于strtok 影响输入缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆