sizeof和strlen

本文深入探讨了C++中字符串的大小计算、数组使用、字符串拷贝、内存拷贝及数组指针操作,通过具体示例展示了如何正确处理字符串和内存数据。
#include <iostream>
#include <memory.h>

using namespace std;

/* */
void test(){
	char *a = "hello";
	char b[] = {'h','e','l','l','o','\0'};
	char c[] = "hello";
	
	cout<<sizeof(a)<<endl;	//4
	cout<<sizeof(b)<<endl;	//6
	cout<<sizeof(c)<<endl;	//6(注意这个是6,计算大小的时候包含进去了'\0')
	cout<<strlen(a)<<endl;	//5
	cout<<strlen(b)<<endl;	//5(若不加'\0'结尾,则结果不确定)
	cout<<strlen(c)<<endl;	//5(若不加'\0'结尾,则结果不确定)
}

/* */
void testArray(){
	int a[][4] = {{1,2,3},{1},{2,3},{1,3}};
	int b[][3] = {{1,2,3},{1},{2,3},{1,3}};
	cout<<"sizeof(a):"<<sizeof(a)<<endl;
	cout<<"sizeof(a):"<<sizeof(b)<<endl;
}

/* */
void testStrcpy(){
	char *a = "hello";
	char *b;
	//b = (char *)malloc(sizeof(char)*strlen(a));	//can work, but not right
	b = (char *)malloc(sizeof(char)*(strlen(a)+1));
	strcpy(b,a);
	cout<<b<<endl;
}

void testMemCpyMove(){
	//char *a = "0123456789"; //error,字符串常量不能修改
	char a[] = "0123456789";  //字符数组可以修改,不是存在常量区
	
	memcpy(a+4,a,6);
	cout<<"a:"<<a<<endl;	//can work: 0123012345

	char b[] = "0123456789"; 
	memmove(b+4,b,6);
	cout<<"b:"<<b<<endl;	//can work: 0123012345
}
/*  */
void testArrayPointerXXX(int a[]){
	cout<<sizeof(a)<<endl; //4
}

int main(){
	int a[] = {2,4,5,3,9,13,8,6};

	cout<<"测试数组"<<endl;
	cout<<sizeof(a)<<endl; //32,数组
	testArrayPointerXXX(a);

	test();
	testArray();

	cout<<"测试字符串拷贝函数"<<endl;
	testStrcpy();

	cout<<"测试内存拷贝函数"<<endl;
	testMemCpyMove();
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值