gpt4 book ai didi

c - 从 main 传递到函数时显示不同的大小

转载 作者:行者123 更新时间:2023-11-30 21:11:50 24 4
gpt4 key购买 nike

#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,而在 function 中变为 8?我可以让谁使两个结果相同?

我什至尝试使用 Fashion(int input1[]) 但结果相同。

最佳答案

这与不同的打字有关。 sizeof 是编译器运算符,而不是运行时函数。

a 的类型为 int[5],它正确地导致大小为 5*4 = 20

input1 的类型为 int *,其大小与 void * 相同。 sizeof(int *) = sizeof(void *) 在 32 位系统上通常为 4,在 64 位系统上通常为 8(其中你的似乎是)。

通常,当将数组传递给函数时,您将指针传递给第一个元素(如在函数中),另外还将数组的长度作为单独的参数传递。

关于c - 从 main 传递到函数时显示不同的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17233176/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com