查找标记(指针和数组名作为参数的区别)

本文深入探讨了C++中使用`strtok()`函数进行字符串分割的方法,包括如何有效管理内存以避免常见错误。通过实际代码示例,解释了如何在不修改原始字符串的情况下正确分割字符串,以及如何避免内存泄漏问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


using namespace std;


/*
void print_tokens( char *line )
{
static char whitespace[] = " \t\f\r\v\n";
char *token ;
for( token = strtok( line, whitespace ); token != NULL ; token = strtok( NULL, whitespace ) )
cout<<"Next token is "<< token<<endl;
}
*/


void print_tokens(const char *line )
{
static char whitespace[] = " \t\f\r\v\n";
char *token;
char *linetmp = (char *)malloc(sizeof(char) * (strlen(line)+1));//分配内存
strcpy(linetmp, line);//复制一个副本
for( token = strtok(linetmp, whitespace); token != NULL ; token = strtok( NULL, whitespace ) )
{
cout<<"Next token is "<< token<<endl;
}
free(linetmp);
}
/*先看帖子:http://blog.csdn.net/libuding/article/details/5870089
**再看:http://www.cnblogs.com/hoys/archive/2011/09/19/2180999.html
*/


void main()
{
char str2[] ="hello world we";
print_tokens( str2 );


/************************************************************************************************
char *str1 ={ "hello world we"};
print_tokens( str2 );
**会出现内存问题,非常难理解!!!
**,当使用char *test2 = "feng,ke,wei"作为第一个参数传入时,在位置①处, 由于test2指向的内容保存在文
**字常量区,该区的内容是不能修改的,所以会出现内存错误. 而char test1[] = "feng,ke,wei" 中的test1指
**向的内容是保存在栈区的,所以可以修改.
**************************************************************************************************/


system("pause");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值