关于char数组 字符串等相关知识

这篇博客探讨了C++中char数组和字符串的相关知识,包括内存分配、初始化和输出。通过示例代码展示了如何使用new操作符创建char数组,并填充数值,然后输出数组的地址和内容。博主还讨论了不同方式打印数组元素的区别。

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

#include <stdlib.h>
#include <stdio.h>
#include
using namespace std;

//对于输出的问题
int main()
{
char* buffer = new char[20];
if (NULL == buffer)
{
printf(“allocate memory failed\n”);
}
int i = 0;
for (i = 0; i < 20;i++)
{
buffer[i] = i; //01234…19
}
//输出buffer中的值
//如果
printf(“buffer address=%#x \n”,buffer); //直接这样写是输出buffer的地址
//printf("*buffer =%c \t *(buffer+1) \n", buffer,(buffer+1));
printf("*buffer=%d \t *(buffer+1)=%d \n", *buffer, *(buffer + 1)); //这样写是输出buffer[0] 输出第一个字符

//我实际想输出整个字符串 不使用for输出  
//使用new buf出来的  只能使用for类似的输出 不好直接输出根据数据名直接输出
printf("-----------------1------------------\n");
for (i = 0; i < 20;++i)
{
	printf("%d",buffer[i]);
}
printf("\n");

printf("-----------------2------------------\n");
for (i = 0; i < 20;++i)
{
	printf("%d", buffer[i] + '0');  //'0'==48  输出%d,输出的是int值(对应的ascii值)
}
printf("\n");

printf("-----------------3------------------\n");
for (i = 0; i < 20; ++i)
{
	printf("%c", buffer[i] + '0');  //输出%c 输出的是ascii值对应的字符 之后就是abcd....这样是错误的 我需要的是10 11 12...
}
printf("\n");

printf("-----------------4------------------\n");
for (i = 0; i < 20; ++i)
{
	printf("%d", buffer[i] + 48);
}
printf("\n");

printf("-----------------5------------------\n");
for (i = 0; i < 20; ++i)
{
	printf("%c", buffer[i] + 48);
}
printf("\n");


if (buffer != NULL)
{
	delete[] buffer;
	buffer = NULL;
}

//
char s[] = "hello";
cout << s << endl;
printf("s=%s \n",s);

char tt[] = {'5','6','7','8'};
cout << tt << endl;		//乱码
printf("tt=%s \n",tt);  //乱码


string t = "world";
printf("t=%s \n", t);  //乱码
printf("t=%s \n",t.c_str()); //world   printf只能输出基本数据类型
//



char s1[] = {1,2,3,4};
char s2[] = {'1','2','3','4'};
for (int j = 0; j < 4;++j)
{
	//cout << s1[j] << '\t';     //这样写是不会正确输出的 数组中的数值是int
	cout << s1[j] + '0' << '\t'; //这样写输出是ascii值 49 50 51 52 因为我将int转换为其对应的ascii值
	printf("%d \t", s1[j]);
}
printf("\n");

for (int k = 0; k < 4;++k)
{
	cout << s2[k] << '\t';
	printf("%c \t",s2[k]);
}
printf("\n");

//

system("pause");
return 1;

}

/*
输出结果:

buffer address=0x1153d70
*buffer=0 *(buffer+1)=1
-----------------1------------------
012345678910111213141516171819
-----------------2------------------
4849505152535455565758596061626364656667
-----------------3------------------
0123456789:;<=>?@ABC
-----------------4------------------
4849505152535455565758596061626364656667
-----------------5------------------
0123456789:;<=>?@ABC
hello
s=hello
5678烫烫烫烫hello
tt=5678烫烫烫烫hello
t=赧?
t=world
49 1 50 2 51 3 52 4
1 1 2 2 3 3 4 4
请按任意键继续. . .
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值