char* 、const char* 、char []、string互相转换使用

17.11 — C-style string symbolic constants – Learn C++

char* X= "ssss":X是指向存放 字符串常量 ssss的地址,可以直接使用char*变量修改该地址处的内容

char* ptr = "sssss1";
char ptrarray[10] = "ssssss2";

// ptrarray = "sssss";  //这样是错误的,必须用strcpy
strcpy(ptrarray,"aaaaaa2");
ptr = "aaaaaa2";
cout << ptrarray << endl;
cout << ptr << endl;

const char * 无法直接赋值给char*,但是反过来就可以

string rootFilePath = "A:/Mini_API/PAT_Convert/*";

char *fliepath = rootFilePath.c_str(); // 这一句时错误的,c_str()返回的是一个const char*

const char *fliepath = rootFilePath.c_str(); // 必须这样使用才行

char[] X=  "ssss":是直接将字符串常量SSSS给X,这些常量存在内存中的常量区,不能直接修改char[]中的内容,这些内容是常量

#include <iostream>
#include <cstring>
using namespace std;

int main(){

	char x[10];
	char x1[10];
	char x2[10];
	
	char *y[3] ={x, x1, x2};//使用数组名其实保存的是数组首元素的地址
	cin >> x;

	// 打印x的值
	cout << x << endl;
	cout << *y << endl;
	cout << y[0] << endl;

	printf("数组的x的地址%x\n",x);
	cout << &x << endl;  //打印整个数组的地址,其实就是数组首元素的地址
	printf("%x\n",&x[0]);
	cout << y << endl;  //打印指针数组的首元素,这里元素全部都是地址
	printf("数组的x的地址%x,%x\n", *y,y[0]);

	strcpy(x2, y[0]);
	cout << x2 << endl;;
	printf("%s",x2);
	// cout << *y[0] << endl;

	return 0;
}

char * 、char[]和string转化

char* 可以直接赋值给string ,反过来则不行。

char[]可以直接赋值给char* ,反过来不行。因为char[],不可以直接赋值修改。

char array_rootpath_floor[] = "A:/Mini_API/PAT_Convert/";
char *p_rootpath_floor = (char*)"A:/Mini_API/PAT_Convert/";

string str_rootpath_floor2_bak = (char*)array_rootpath_floor;
string str_rootpath_floor2 = p_rootpath_floor;

 char * 和char []的使用

    char *str= "V1.0.1";

    printf("%c\n",*str);//输出首字符

	printf("%s\n",str);//输出整串字符

	printf("%p\n",str);//输出字符串首字符地址

	printf("%p\n",&str);//输出指针str的地址
    char *the_path = (char*)__FILE__;
    const char *the_date = __DATE__;
    const char *the_time = __TIME__;
    const char *the_ver = "V1.0.1";
    printf("\r\nFile:%s\nCompileTime:%s-%s\nCompileVersion:%s\n",the_path,the_date,the_time,the_ver);

    char the_path[] = __FILE__;
    char the_date[] = __DATE__;
    char the_time[] = __TIME__;
    char the_ver[] = "V1.0.1";
    printf("\r\nFile:%s\nCompileTime:%s-%s\nCompileVersion:%s\n",the_path,the_date,the_time,the_ver);

指针自加的使用

自加只能放在 =的右侧使用,不可以对 = 左侧的值使用++,另外指针也不支持 指针加1

uint8_t *CDC_USART_RxBuffer = 0

CDC_USART_RxBuffer = (uint8_t*)malloc(RX_Buffer_Len * sizeof(uint8_t));

CDC_USART_RxBuffer  = CDC_USART_RxBuffer  + 1;//这是错误的用法

//指针分配空间后,对内部赋值可以采用下面的方法
memcpy(CDC_USART_RxBuffer + USART_RX_LEN,RxBuff[0],1);

// malloc后一定清空内存,避免泄露
free(CDC_USART_RxBuffer);

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值