首页 > 解决方案 > 使用指向字符的指针作为 strtok 的参数

问题描述

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

如果我将字符串初始化为s2s3程序运行良好。但是,如果我使用指向字符s1的指针作为程序获取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出错。

完整代码如下:

#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)

strtokman页面:char *strtok(char *str, const char *delim);

请帮助理解这个问题。

标签: carraysstringpointersstrtok

解决方案


Battosai,首先您需要使用武士刀的反面通过使用可读/可写区域来实现目标。如果您不这样做,除非编译器/操作系统(神谷薰)不阻止您, 否则Shishio Makoto可能会通过Sojiro Seta毁掉对您和您周围重要的人,生活在您的记忆中,例如Sanosuke SagaraYahiko Myojin

strtok写入您给它的字符串 - 用 null 覆盖分隔符并保留指向字符串其余部分的指针。

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.

推荐阅读