zoukankan      html  css  js  c++  java
  • 蛋疼的strtok函数

    解一道题的时候要用到字符串分割,但是c标准库里没有类似java,python中的split()函数啊,自己写的话要用到strtok()这个函数,这可真是个让人蛋疼的函数。下面说为什么。

    给出我的原始代码

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <string.h>
     4 
     5 int  split(char **arr,char *str,const char *del)
     6 {
     7     int count =0;
     8     char *s  = strtok(str,del);
     9     while (s)
    10     {
    11         *arr++ = s;
    12         s = strtok(NULL,del);
    13         count++;
    14 
    15     }
    16     return count;
    17 }
    18 int main()
    19 {
    20     //printf("Hello world!
    ");
    21     char *str = "wo shi lian wen long";
    22     char *save[10] ;//= {};
    23     memset(save,0,sizeof(save));
    24    char buff[20];
    strcpy(buff,str);
    25 const char *del = " "; 26 int i = split(save,buff,del); 27 int j; 28 29 for (j=0;j<i;j++) 30 { 31 printf("%s ",save[j]); 32 } 33 34 return 0; 35 }

    gcc编译器显示我在调用strtok()的时候出现段错误。

    百思不得骑姐,最终在stackoverflow上找到了答案。

    http://stackoverflow.com/questions/8957829/strtok-segmentation-fault

    原来是因为我在调用strtok的时候会改变字符串的字面值,但这是不被允许的。因为"wo shi lian wen long"是常量字符串,被存储在只读空间中,str是个可以读写的指针,用非常量字符指针指向常量字符串本身在逻辑上就是错误的,对常量字符串进行读写操作(即应用于strtok())造成了实际错误。我的代码中给出了改正的方法,strcpy(buff,str),因为buff是个数组,str指向的常量字符串存储在数组中,而数组是在数据区储存,所以可以对数组内的数据进行读写。按照同样的思路,char buff[] = str;也可以改正错误。

    想要改写指针指向的空间,就要保证指针指向的是可写的空间,强行改写只读空间是不鼓励的。

  • 相关阅读:
    KMP
    图论知识,博客
    POJ 2318/2398 叉积性质
    CF821 E. Okabe and El Psy Kongroo 矩阵快速幂
    CF821 D. Okabe and City 图 最短路
    CF821 C. Okabe and Boxes 栈模拟
    CF821 A. Okabe and Future Gadget Laboratory 水
    Atcoder arc077 D
    Atcoder #017 agc017 D.Game on Tree 树上NIM 博弈
    Atcoder #017 agc017 B.Moderate Differences 思维
  • 原文地址:https://www.cnblogs.com/lianwl/p/3205159.html
Copyright © 2011-2022 走看看