strlen、sizeof区别
sizeof计算 包括 "/0"
strlen计算 不包括 "/0"
sizeof遇到 最后一个 "/0"停止
strlen遇到 第一个 "/0"停止
char str[20]="0123456789";
sizeof(str); // 20
strlen(str); // 10
char *ss = "0123456789";
sizeof(ss); // 4 指针ss的空间大小
sizeof(*ss); // 1 第一个字符‘0’占的空间
strlen(ss); // 10 字符串长度
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include <bits/wordsize.h> //
int main()
{
char *s = "helloworld";
char a[30] = "";
char b[] = "***";
char d[] = "helloworld"; // sizeof 会计算在后面添加的 \0
char e[] = {'h','e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'};
printf("s: %d %d\n", sizeof(*s), strlen(s));
printf("d: %d %d\n", sizeof(d), strlen(d));
printf("e: %d %d\n", sizeof(e), strlen(e));
char str[] = "\\\0";
char *p = str;
int n = 1000;
printf("str:%d\n p:%d\n %d\n %d\n", sizeof(str), sizeof(p), sizeof(n), strlen(str));
double doub = 3.1415926;
printf("double: %d\n", sizeof(doub));
unsigned long pulArray[]= {6,7,8,9,10};
unsigned long *pulPtr;
char c1[]={'I',' ','a','m',' ','h','a','p','p','y','\0'};
char c2[]="I am happy";
printf("c1: %d %d %s\n", sizeof(c1), strlen(c1), c1);
printf("c2: %d %d\n", sizeof(c2), strlen(c2));
pulPtr = pulArray;
*(pulPtr+2)+=2;
printf("p: %d,%d\n", *pulPtr, *(pulPtr+2));
if(__WORDSIZE == 32)
{
printf("machine 32bit\n");
}
if(__WORDSIZE == 64)
{
printf("machine 64bits\n");
}
printf("a: %d %d\n", sizeof(a), strlen(a));
memcpy(a, s, strlen(s)+1);
printf("%s\n", a);
printf("%d\n", sizeof(int));
memcpy(d, b, strlen(b)); // strlen(b)+1
printf("%s\n", d);
return 0;
}
s: 1 10
d: 11 10
e: 10 10
str:3
p:8
4
1
double: 8
c1: 11 10 I am happy
c2: 11 10
p: 6,10
machine 64bits
a: 30 0
helloworld
4
***loworld