#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;
}
分享到:
相关推荐
分析sizeof和strlen具体区别(源码和解析)
总结sizeof 和strlen的区别: sizeof(...)是运算符,在头文件中typedef为unsigned int,其值在编译时即计算好了,参数可以是数组、指针、类型、对象、函数等。它的功能是:获得保证能容纳实现所建立的最大对象的字节...
sizeof 和strlen的区别
此文档对sizeof和strlen做了详细的说明和比较,同时带有实例进行验证,适合初学者使用
本文介绍的是sizeof与strlen区别
本文档介绍了sizeof和strlen的区别和联系,其中sizeof为运算符,strlen为C语言库函数。而sizeof在计算字符串的长度时,将结束符'\0'也算在内,但是strlen不将它算在内。
主要是下载分不够了,希望上传代码赚几分回来。 小白yige,这些代码是学习C的时候习题代码,没有什么实用价值,高手就别来笑话我了,特别是那些和我一样还在自学的朋友相互之间交流一下。
本文通过示例简单分析了4种情况下C语言中sizeof 和 strlen的区别,算是个人经验的一个小小的总结,如有遗漏还请大家告知。
sizeof与strlen的区别共4页.pdf.zip
c语言中最常遇到的问题是字符串处理问题,特别是字符串长度:sizeof与strlen.两者使用时一定要区分开,否着会很容易出错。本文对两者的区别做了详细介绍。
c语言strlen转义字符,转义字符 & sizeof & strlen-CSDN博客.mhtml
本文介绍了了数组的长度问题,在使用sizeof()和strlen()时的不同之处。
sizeof()和strlen()经常会被初学者混淆,但其中有有很大区别: sizeof() 1. sizeof()【操作数所占空间的字节数大小】是一种c中的基本运算符。 可以以类型、指针、数组和函数等作为参数。 头文件类型为unsigned int。...
1. strlen 是个函数,只能以 char* (字符串)作为参数,来计算指定字符串 str 的度,但不 2. sizeof 是个单运算符,它的参数可以是数组
## sizeof和strlen的区别 sizeof是一个操作符,strlen是库函数。 sizeof的参数可以是数据的类型,也可以是变量,而strlen只能以结尾为‘0‘的字符串作参数。 编译器在编译时就计算出了sizeof的结果。而strlen函数...