数组的一系列运算 【sizeof计算 strlen计算】

  • //一维数组
int arr[] = { 1, 2, 3, 4 };
printf("%d\n", sizeof(arr));//16
printf("%d\n", sizeof(arr+0));//4
printf("%d\n", sizeof(*arr));//4
printf("%d\n", sizeof(arr+1));//4
printf("%d\n", sizeof(arr[1]));//4
printf("%d\n", sizeof(&arr));//4
printf("%d\n", sizeof(*&arr));//16
printf("%d\n", sizeof(&arr+1));//4
printf("%d\n", sizeof(&arr[0]));//4
printf("%d\n", sizeof(&arr[0]+1));//4

输出结果:这里写图片描述


  • //字符数组
    类型 1
char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
printf("%d\n", sizeof(arr));//6
printf("%d\n", sizeof(arr + 0));//4
printf("%d\n", sizeof(*arr));//1
printf("%d\n", sizeof(arr[1]));//1
printf("%d\n", sizeof(&arr));//4
printf("%d\n", sizeof(&arr + 1));//4
printf("%d\n", sizeof(&arr[0] + 1));//4

printf("%d\n", strlen(arr));//23
printf("%d\n", strlen(arr+0));//23
//printf("%d\n", strlen(*arr));//error
//printf("%d\n", strlen(arr[1]));//error
printf("%d\n", strlen(&arr));//23
printf("%d\n", strlen(&arr+1));//17
printf("%d\n", strlen(&arr[0]+1));//22

输出结果:这里写图片描述


类型 2

char arr[] = {"abcdef"};
printf("%d\n", sizeof(arr));//7
printf("%d\n", sizeof(arr + 0))//4;
printf("%d\n", sizeof(*arr));//1
printf("%d\n", sizeof(arr[1]));//1
printf("%d\n", sizeof(&arr));//4
printf("%d\n", sizeof(&arr + 1));//4
printf("%d\n", sizeof(&arr[0] + 1));//4

printf("%d\n", strlen(arr));//6
printf("%d\n", strlen(arr + 0));//6
//printf("%d\n", strlen(*arr));//error
//printf("%d\n", strlen(arr[1]));//error
printf("%d\n", strlen(&arr));//6
printf("%d\n", strlen(&arr + 1));//12
printf("%d\n", strlen(&arr[0] + 1));//5

这里写图片描述


类型 3

char *p = "abcdef";
printf("%d\n", sizeof(p));//4
printf("%d\n", sizeof(p+1));//4
printf("%d\n", sizeof(*p));//1
printf("%d\n", sizeof(p[0]));//1
printf("%d\n", sizeof(&p));//4
printf("%d\n", sizeof(&p + 1));//4
printf("%d\n", sizeof(&p[0] + 1));//4

printf("%d\n", strlen(p));//6
printf("%d\n", strlen(p + 1));//5
//printf("%d\n", strlen(*p));//error
//printf("%d\n", strlen(p[0]));//error
printf("%d\n", strlen(&p));//3
printf("%d\n", strlen(&p + 1));//15
printf("%d\n", strlen(&p[0] + 1));//5

结果输出:这里写图片描述


  • //二维数组
int arr[3][4] = {0};//48
printf("%d\n", sizeof(arr));//4
printf("%d\n", sizeof(arr[0][0]));//16
printf("%d\n", sizeof(arr[0]));//4
printf("%d\n", sizeof(arr[0]+1));//4
printf("%d\n", sizeof(arr+1));//4
printf("%d\n", sizeof(&arr[0]+1));//4
printf("%d\n", sizeof(*arr));//16
printf("%d\n", sizeof(arr[3]));/16

结果输出:这里写图片描述


总结:
数组名代表数组的时候只有两种情况:

sizeof(数组名),这里的数组表示整个数组
&数组名,这里的数组表示整个数组


猜你喜欢

转载自blog.csdn.net/zhang21722668/article/details/81637714