c语言 Mingw 中 strtok的一个问题
时间:2010-10-03 来源:Safrain
int main() {
        char *s = "Golden Global View";
        const char *d = " ";
        char *p;
        p = strtok(s, d);
        while (p) {
                printf("%s\n", p);
                p=strtok(NULL, d);
        }
        getchar();
        return 0;
}
使用Mingw+Eclipse写了上面一段c代码 可是运行到第一个strtok的时候,程序崩溃了,时好时坏。
查了半天发现了问题:
char *s = "Golden Global View";
s是“不可写”的,需要复制一下,变成“可写”的
如下
int main() {
        char *s;
        s = malloc(30);
        strcpy(s, "Golden Global View");
        const char *d = " ";
        char *p;
        p = strtok(s, d);
        while (p) {
                printf("%s\n", p);
                p = strtok(NULL, d);
        }
        return 0;
}
上面的程序中s被复制了,strtok就不会报错了。
strdup能达成同样的目的。
 相关阅读 更多 + 
    
   排行榜 更多 + 
    
    
  









