c - 使用指向字符的指针作为 strtok 的参数
问题描述
我尝试使用strtok
函数拆分字符串。但是如果我使用指向字符的指针作为这个函数的参数,程序就会失败。
如果我将字符串初始化为s2
或s3
程序运行良好。但是,如果我使用指向字符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)
strtok
从man
页面:char *strtok(char *str, const char *delim);
请帮助理解这个问题。
解决方案
Battosai,首先您需要使用武士刀的反面通过使用可读/可写区域来实现目标。如果您不这样做,除非编译器/操作系统(神谷薰)不阻止您, 否则Shishio Makoto可能会通过Sojiro Seta毁掉对您和您周围重要的人,生活在您的记忆中,例如Sanosuke Sagara,Yahiko 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.
推荐阅读
- xml - E: 包 'gccxml' 没有安装候选
- android - 如何在Android中执行单击ListView元素的按钮
- android - 在xamarin android中填充软输入调整大小
- javascript - 我在哪个 iframe 中?
- http - 我可以在 nginx 上游同时使用 HTTP 和 HTTPS 吗?
- python - 检查 IF 中的空 str
- python - 计算给定时间跨度内的触发器数量
- c++ - 获取非托管 C/C++ 中已签名 EXE 的 X509 代码签名证书序列号
- wordpress - SASS WordPress 的 Owl Carousel 安装
- reactjs - 在 Modal 中更改 Element 的类