关于C语言strtok/strtok_s函数不得不知的一件事
C语言 函数 关于 不知 不得 一件
2023-09-14 09:13:08 时间
本人就职于国际知名终端厂商,负责modem芯片研发。
在5G早期负责终端数据业务层、核心网相关的开发工作,目前牵头6G算力网络技术标准研究。
文章目录
strtok/strtok_s
以strtok为例
前几天使用strtok函数,程序一直报告Segmentation fault
错误程序如下:
#include<string.h>
#include<stdio.h>
int main()
{
char * str = "this is test code";
char *res=str;
while(res = strtok(res , " "))
{
printf("%s\n",res);
res = NULL;
}
return 0;
}
之后查看了C语言标准文档,发现了问题所在,下面是strtok的声明格式
char *strtok(char * restrict s1,const char * restrict s2);
可以看到第一个参数s1是char *类型,第二个参数s2是const char *类型
const char * 是字面量参数,就是上面错误code中的
char * str = "this is test code";
char * 是指向堆或栈中的一个内存地址,可以是
char str[] = "this is test code";
或者
char * str = malloc(sizeof("this is test code"));
memcpy(str, "this is test code",sizeof("this is test code"));
正确code如下👇
#include<string.h>
#include<stdio.h>
int main()
{
char str[] = "this is test code";
//或者下面的code
//char * str = malloc(sizeof("this is test code"));
//memcpy(str, "this is test code",sizeof("this is test code"));
char *res=str;
while(res = strtok(res , " "))
{
printf("%s\n",res);
res = NULL;
}
return 0;
}
相关文章
- C语言 list 链表
- 清览题库--C语言程序设计第五版编程题解析(1)
- C语言教程学习36-40节 字符串函数+结构
- C语言例题:编写程序将两个字符串进行连接,不使用strcat函数
- C语言随机数生成:rand和srand函数
- 【安全算法之MD5】MD5摘要运算的C语言源码实现
- 【经验分享】一个实用的C语言宏定义技巧写法
- C语言 | 动图演示十大经典排序算法(含代码)
- C语言函数返回 1 和返回 0 哪个好?
- Linux下轻松操作之C语言方向键指南(linuxc方向键)
- 字符数组和字符串的区别,C语言字符数组和字符串区别详解
- puts和fputs函数及其区别,C语言puts和fputs函数详解
- C语言线程函数
- C语言modf()函数:提取浮点数的小数和整数部分
- Linux C语言编程中的常用函数(linuxc常用函数)
- 探索Linux中C语言的功能知识(linux c语言函数)
- C语言中给Mysql变量赋值的方法(c中mysql变量赋值)
- C语言编程检查MySQL运行状态(c mysql状态判断)
- C语言MySQL中使用求和函数输出结果(c mysql求和输出)
- MySQL函数使用指南C语言编程者的最佳实践(c mysql函数大全)
- 如何解决C语言,函数名与宏冲突
- C语言中字符串常用函数strcat与strcpy的用法介绍
- C语言之free函数以及野指针介绍
- linux下C语言中的mkdir函数与rmdir函数
- C语言实现两个递减数列中寻找某一个数