c_str 的问题

先看看代买:

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string.h>
using namespace std;

int main()
{
	string str = "hello world";

	const char *s = str.c_str();
	printf("s = %s\n",s);

	str = "Hello World!";
	printf("s = %s\n",s);

	system("pause");
	return 0;
}

输出结果:

s = hello world

s = Hello World!

发现当执行 const char *s = str.c_str();以后,再修改str的值,s的值也会被更改。修改了str之后,s取得的数据就是垃圾数据。跟预期的值不一样。

究其原因是因为c_str()函数返回的是一个指针,指向的是字符串str的首地址。所以当str改变的时候,指针指向内容也就随之变化。

那用什么方法能够避免这种错误呢?

看:

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string.h>
using namespace std;

int main()
{
	string str = "hello world";
	char s[20];
	strncpy(s, str.c_str(), strlen(str.c_str()) + 1);
	printf("s = %s\n", s);

	str = "HELLO WORLD";
	printf("s = %s\n", s);

	system("pause");
	return 0;
}

运行结果:

s = hello world

s = hello world

通过strcpy或者strncpy都可以有效的解决 产生垃圾数据的问题。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值