代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str[] = "hello";
char* p1 = "hello";
char* p2 = "hello";
int size_str = 0;
int size_p1 = 0;
int size_p2 = 0;
int len_str = 0;
int len_p = 0;
size_str = sizeof(str);
size_p1 = sizeof(p1);
p2 = (char*)malloc(100);
size_p2 = sizeof(p2);
len_str = strlen(str);
len_p = strlen(p1);
printf("size_str = %d\n",size_str);
printf("size_p1 = %d\n",size_p1);
printf("size_p2 = %d\n",size_p2);
printf("len_str = %d\n",len_str);
printf("len_p = %d\n",len_p);
return 0;
}
运行结果:
总结:
① 用sizeof,只要是指针,无论什么类型 ,无论是否用malloc,无论malloc开辟了多大空间,在32位下结果永远是4,在64位下永远是8.
②sizeof计算字符数组大小,会将'\0'也计算在内,比如字符数组中是"hello"6个字符,那么结果是6,因为还有一个'\0'要算在内。其实严格来讲应该这样的:sizeof(str)/sizeof(char) 或 sizeof(str)/sizeof(str[0]),这样才是这个数组的大小,因为char形占一个字节,所以除不出无所谓。
③ 用strlen,他只计算里面字符的个数,到'\0'结束,'\0'这个字符不计算在内