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

标签 c arrays pass-by-reference sizeof

#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/

相关文章:

C 指针表示法与数组表示法比较 : When passing to function

c++类只能通过引用传递

C编程printf在使用嵌套循环时不打印

c - 将不正确的字符写入帧缓冲区

java - 从包含对象数组的二进制文件中读取特定索引

php - 如何查询多个变量以在 Codeigniter 的 View 中显示

c - 标记一个字符串以作为 char * 传递给 execve()

c - C 中 malloc 的内存泄漏问题

c++ - 如何将对象传递给 C++ 中的函数?

function - 尝试取消引用一个接口(interface),该接口(interface)是指向后端结构对象的指针,因此我可以按值传递给函数