c - 数组的长度在传递函数后发生变化

标签 c arrays

我使用以下代码将数组传递给函数并在调用函数之前和之后打印其大小:

#include <stdio.h>

int passing_array(int array[]) {
    int size = sizeof(array);
    printf("The size after passing: %d\n", size);
}

int main () {
    int a[] = {1, 2, 3};

    int size = sizeof(a);
    printf("The size before passing: %d\n", size);

    passing_array(a);

    return 0;
}

运行代码后,我得到了一个奇怪的结果:

The size before passing: 12

The size after passing: 8

我的问题是:为什么数组的大小从12变成了8?

最佳答案

int passing_array(int array[]) {
    int size = sizeof(array);
    printf("The size after passing: %d\n", size);
}

相同
int passing_array(int* array) {
    int size = sizeof(array);
    printf("The size after passing: %d\n", size);
}

因此,size 是指针的大小。

关于c - 数组的长度在传递函数后发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32598769/

相关文章:

c - 将空间扫描为字符

C++ Box2D - 单独放置时不受重力影响的动态物体

C++ 初始化二维结构数组

javascript - 如何检查数组对象的属性是否与另一个对象数组中的值之一匹配

c# - 多种类型的数组 C#(包括其他数组)

c - unistd.h 读取()函数 : How to read a file line by line?

c++ - 使用 Arduino/C++ 从 SD 卡上的文件中读取一个 float

c - 当来自 C# 时,试图理解在 C 中添加到数组

javascript - 如何将复选框中的值添加到数组

c - 为什么 malloc(0) 在 Windows 中返回一个非空地址?