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

标签 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;
            }
        }
    }
}

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

最佳答案

sizeof 返回您传递给它的内容的内存大小。返回值为...

measured in the number of char-sized storage units required for the type

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

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

int a[3];
size_t n = sizeof(a) / sizeof(a[0]);

注:如dbush在下面的评论中提到:

...this only works if the array is not a paramerer to a function. In that case the array decays to a pointer and sizeof(array) evaluates to the size of a pointer.

关于c - 为什么 sizeof() 不返回数组的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52415058/

相关文章:

c - 流音频 udp C

c - union 数据存储如何工作。得到令人困惑的输出

javascript - 搜索数组时出现问题

python - 在python中将2d数组转换为3d数组

java - 按文件名对文件路径数组进行排序

algorithm - 壳牌比。希伯德时间复杂度比较

html - HTML 处理时出错

c - 在 C 头文件中使用定义?

c - 将指针数组传递给函数

c - 基于 C - 仅在第三列上对 10x10 随机整数矩阵进行排序