代码1:
#include <stdio.h> int main() { char *str = "GeeksQuiz"; char str1[] = "GeeksQuiz"; char str2[] = { 'G', 'e', 'e', 'k', 's', 'Q', 'u', 'i', 'z' }; int n = sizeof(str) / sizeof(str[0]); //4, str是一个指针 int n1 = sizeof(str1) / sizeof(str1[0]); //10, str1是一个数组,注意'\0' int n2 = sizeof(str2) / sizeof(str2[0]); //9,数组, printf("n = %d, n1 = %d, n2 = %d", n, n1, n2); return 0; }
In main, the name array is an array so you get the size in bytes of the array with sizeof.
However, an array decays to a pointer when passed to a function, so you get sizeof(int*) inside the function.
代码2:
#include<stdio.h> /*数组名当函数参数传递时,会被当做指针处理*/ void func1(int a[]) { printf("%d\n",sizeof(a)); // 4 } void func2(int *a) { printf("%d\n", sizeof(a)); } int main() { int array[] = { 1, 2, 3 }; printf("%d\n", sizeof(array)); // 12 func1(array);//4 func2(array);//4 return 0; }