sizeof和strlen的比较

sizeof和strlen的比较

例子一、

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

typedef struct Stu
{
	int i;
	int j;
	char k;
}MyStu;


int main()
{
	char arr[20]="hello world!"; 
	cout<<"strlen(arr) : "<<strlen(arr)<<endl;  //返回12,一共有12个字符,不包括'\0'
	cout<<"sizeof(arr) : "<<sizeof(arr)<<endl;  //返回20,因为系统给数组分配了20个字节


	cout<<"strlen(\"hello\") : "<<strlen("hello")<<endl;  //返回字符串长度5
	cout<<"sizeof(\"hello\") : "<<sizeof("hello")<<endl;  //返回6,实际的存储空间还包含最后面的'\0'

	char *p="hello";
	cout<<"strlen(p) : "<<strlen(p)<<endl;  //返回字符串长度5
	cout<<"sizeof(p) : "<<sizeof(p)<<endl;  //返回指针p的内存空间大小4个字节
	cout<<"这个是内存对齐的结果"<<sizeof(MyStu)<<endl;  //结果 12  ===》内存补齐
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_35433716/article/details/89384466