zl程序教程

您现在的位置是:首页 >  后端

当前栏目

关于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;
}

在这里插入图片描述