穆穆青风至 2022-01-12 19:37 采纳率: 97.4%
浏览 38
已结题

c语言,sizeof关键字的用法

# include<stdio.h>
#include<string.h>
#pragma warning(disable:4996)
int main()
{
    int a[] = { 5,4,4,4};
    int k;
    int m, n;
    int sort(int a[]);
    printf("长度%d\n", sizeof(a));
    sort(a);
    return 0;
}
int  sort(int a[]) {
    printf("长度%d\n", sizeof(a) );
    for (int i = 0; i < sizeof(a)/sizeof(int); i++) {
        printf("%d\n", a[i]);
    }
    return 0;
}


为啥两次输出同一个数组,长度变化了

img

  • 写回答

1条回答 默认 最新

  • _GX_ 2022-01-12 19:58
    关注
    #include <stdio.h>
    #include <string.h>
    #pragma warning(disable : 4996)
    int main()
    {
        int a[] = {5, 4, 4, 4};
        int k;
        int m, n;
        int sort(int a[]);
        printf("长度%d\n", sizeof(a)); // 这里的a是数组,所以sizeof(a)返回的是数组的大小
        sort(a);
        return 0;
    }
    int sort(int a[]) // 当数组当作参数传入函数时,这个参数退化为指针
    {
        printf("长度%d\n", sizeof(a)); // 所以这里的sizeof(a)返回的是指针的大小
        for (int i = 0; i < sizeof(a) / sizeof(int); i++)
        {
            printf("%d\n", a[i]);
        }
        return 0;
    }
    

    From https://en.cppreference.com/w/c/language/array#Array-to-pointer-conversion

    When an array type is used in a function parameter list, it is transformed to the corresponding pointer type: int f(int a[2]) and int f(int* a) declare the same function. Since the function's actual parameter type is pointer type, a function call with an array argument performs array-to-pointer conversion; the size of the argument array is not available to the called function and must be passed explicitly:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 1月20日
  • 已采纳回答 1月12日
  • 修改了问题 1月12日
  • 创建了问题 1月12日

悬赏问题

  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?