#include <stdio.h>
#include <string.h>
int fashion (int[]);
main()
{
int a[]={3,2,5,1,3};
int size;
size= sizeof a/sizeof (int);
printf("size of array %d\n",sizeof(a)); //size of the array
printf("size of int %d\n",sizeof(int)); //size of the int
printf("lenght of array %d\n",size); //actual length of the array
fashion(a);
return 0;
}
int fashion(int input1[]) //tried with int fashion(int *input1)
{
int size;
size= sizeof input1/sizeof (int);
printf("\nin function\n");
printf("size of array %d\n",sizeof(input1)); //size of the array
printf("size of int %d\n",sizeof(int)); //size of the int
printf("lenght of array %d\n",size); //actual length of the array
}
以下是代码的输出:
output is
size of array 20
size of int 4
lenght of array 5
In function
size of array 8
size of int 4
lenght of array 2
主函数和函数中的代码都是相同的,但结果不同。
为什么在main函数中更改数组的大小为20,在函数中为8? 谁能使两个结果相同?
我甚至尝试使用Fashion(int input1 [])但结果相同。
答案 0 :(得分:0)
这与不同的打字有关。 sizeof
是编译器操作符,而不是运行时函数。
a
的类型为int[5]
,正确的大小为5*4 = 20
。
input1
的类型为int *
,其大小与void *
相同。 sizeof(int *) = sizeof(void *)
在32位系统上通常为4
,在64位系统上为8
(您的系统似乎是这样)。
通常在将数组传递给函数时,将指针传递给第一个元素(如在函数中),并将数组的长度作为单独的参数传递。