现在的位置: 首页 > 综合 > 正文

sizeof和strlen

2019年10月15日 ⁄ 综合 ⁄ 共 1197字 ⁄ 字号 评论关闭
#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;
}

抱歉!评论已关闭.