为什么sizeof()不返回数组的长度?

cjs*_*neb 1 c arrays sorting sizeof

#include <stdio.h>

int main() {
    int test[3];
    int i;
    test[0]=5;
    test[1]=10;
    test[2]=7;

    printf("array size: %d\n",sizeof(test));
    sortArray(test);

    for(i=0;i<sizeof(test);i++) {
        printf(" %d ", test[i]);
    }
    printf("\n");
}

void sortArray(int number[]) {
    int i,j,a;
    int n = 5;

    for (i = 0; i < n; i++) {
        for (j = i + 1; j < n; j++) {
            if (number[j] < number[i]) {
                a = number[i];
                number[i] = number[j];
                number[j] = a;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我遇到问题的数组是"test"当我运行程序时,"size"总是预期大小的4的倍数.例如:test [3]会输出12的大小.我做错了什么?我也使用code :: blocks作为ide.

Fog*_*zie 5

sizeof返回传递它的内存大小.返回值是......

以该类型所需的字符大小的存储单元数量来衡量

在典型的32位系统中,a char是一个字节,int是四个字节,因此对于类型数组,您将获得四的倍数int.

如果你想要数组的长度,只需要除以类型的大小:

int a[3];
size_t n = sizeof(a) / sizeof(a[0]);
Run Code Online (Sandbox Code Playgroud)

注意:正如以下评论中提到的dbush:

...这仅在数组不是函数的参数时才有效.在这种情况下,数组衰减为指针,sizeof(数组)求值为指针的大小.

  • 请注意,这仅适用于数组*不是*函数的参数.在这种情况下,数组衰减为指针,`sizeof(array)`计算指针的大小. (3认同)