# include<stdio.h>
#include<string.h>
#pragma warning(disable:4996)
int main()
{
int a[] = { 5,4,4,4};
int k;
int m, n;
int sort(int a[]);
printf("长度%d\n", sizeof(a));
sort(a);
return 0;
}
int sort(int a[]) {
printf("长度%d\n", sizeof(a) );
for (int i = 0; i < sizeof(a)/sizeof(int); i++) {
printf("%d\n", a[i]);
}
return 0;
}
为啥两次输出同一个数组,长度变化了
#include <stdio.h>
#include <string.h>
#pragma warning(disable : 4996)
int main()
{
int a[] = {5, 4, 4, 4};
int k;
int m, n;
int sort(int a[]);
printf("长度%d\n", sizeof(a)); // 这里的a是数组,所以sizeof(a)返回的是数组的大小
sort(a);
return 0;
}
int sort(int a[]) // 当数组当作参数传入函数时,这个参数退化为指针
{
printf("长度%d\n", sizeof(a)); // 所以这里的sizeof(a)返回的是指针的大小
for (int i = 0; i < sizeof(a) / sizeof(int); i++)
{
printf("%d\n", a[i]);
}
return 0;
}
From https://en.cppreference.com/w/c/language/array#Array-to-pointer-conversion
When an array type is used in a function parameter list, it is transformed to the corresponding pointer type: int f(int a[2]) and int f(int* a) declare the same function. Since the function's actual parameter type is pointer type, a function call with an array argument performs array-to-pointer conversion; the size of the argument array is not available to the called function and must be passed explicitly: