使用指向字符的指针作为strtok的参数 [英] Using pointer to character as the argument of strtok

查看:95
本文介绍了使用指向字符的指针作为strtok的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 strtok 函数拆分字符串.但是,如果我使用指向字符的指针作为该函数的参数,程序就会失败.

I try to split the string by using strtok function. But the program become failed if i use the pointer to character as the argument of this function.

如果我将字符串初始化为 s2 s3 ,则该程序运行良好.但是,如果我使用指向字符的指针作为 s1 ,则程序会得到 Segmentation fault(核心转储).

If i initialize the string as s2 or s3 the program works well. But if i use pointer to character as s1 the program get Segmentation fault (core dumped).

char *s1 = "1A 2B 3C 4D";
char s2[] = "1A 2B 3C 4D";
char s3[20] = "1A 2B 3C 4D";

问题是其他功能, printf strlen 正常运行,但只有 strtok 出错.

The problem is the other functions, printf and strlen work without failure, but only strtok get error.

下面的完整代码:

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

void split_string(char *s) {
    char * token = strtok(s," ");
    while (token != NULL) {
        printf("%s\n", token);
        token = strtok(NULL, " ");
    }
}

int main()
{
    char *s1 = "1A 2B 3C 4D";
    char s2[] = "1A 2B 3C 4D";
    char s3[20] = "1A 2B 3C 4D";
    printf("size of s1 = %ld, s2 = %ld, s3 = %ld\n", strlen(s1), strlen(s2), strlen(s3));
    printf("s1: %s\ns2: %s\ns3: %s\n",s1,s2,s3);
    printf("split s2: \n");
    split_string(s2);
    printf("split s3: \n");
    split_string(s3);
    printf("split s1: \n");
    split_string(s1);
    return 0;
}

运行后的结果:

size of s1 = 11, s2 = 11, s3 = 11
s1: 1A 2B 3C 4D
s2: 1A 2B 3C 4D
s3: 1A 2B 3C 4D
split s2: 
1A
2B
3C
4D
split s3: 
1A
2B
3C
4D
split s1: 
Segmentation fault (core dumped)

来自 man 页面的

strtok : char * strtok(char * str,const char * delim);

请帮助您了解此问题.

推荐答案

Battousai ,首先,您需要使用武士刀的反面,以使用可读写区域来实现目标.如果您不这样做,除非编译器/OS( Kamiya Kaoru )不会阻止您, Shishio Makoto 可能会通过 Sojiro Seta 破坏对您和您周围重要的人,他们生活在您的记忆中,例如 Sanosuke Sagara Yahiko Myojin.

Battousai, firstly you need to use your reverse side of the katana to achieve your aim by using readable/writable area. If you don't do this, unless the compiler/OS(Kamiya Kaoru) doesn't prevent you, Shishio Makoto may ruin guys important for you and around you via Sojiro Seta, living in your memory such as Sanosuke Sagara, Yahiko Myojin.

strtok 写入您提供的字符串-覆盖带null的分隔符,并保留指向其余字符的指针字符串.

strtok writes into the string you give it - overwriting the separator character with null and keeping a pointer to the rest of the string.

char *s1 = "1A 2B 3C 4D"; // you have a pointer to some read-only characters
char s2[] = "1A 2B 3C 4D"; // same, decay into pointer
char s3[20] = "1A 2B 3C 4D"; // a twenty element array of characters that you can do what you like with.

这篇关于使用指向字符的指针作为strtok的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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