C语言中通过函数的sizeof数组 [英] Sizeof array through function in C

查看:206
本文介绍了C语言中通过函数的sizeof数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定为什么在通过函数传递数组时为什么不能使用sizeof(array)只输出1而不是1000000的值.在将数组传递给函数之前,我打印了sizeof(array)要得到4000000,当我尝试在函数中打印出sizeof(array)时,我只能得到4.我可以在函数和main中遍历数组以显示所有值,但我无法在函数内显示sizeof.我没有正确通过阵列吗?

I'm not sure why I cannot use sizeof(array) when passing the array through my function only outputs a value of 1, instead of 1000000. Before passing the array to the function, I printed out the sizeof(array) to get 4000000 and when I try to printout the sizeof(array) in the function, I only get 4. I can iterate through the array in both the function and the main to display all values, I just cannot display sizeof within the function. Did I pass the array through incorrectly?

#include <stdio.h>
#include <stdlib.h>

int
searchMe(int numbers[], int target)
{
    printf("%d\n", sizeof(numbers));
    int position = -1;

    int i;
    int k = sizeof(numbers) / sizeof(numbers[0]);   

    for (i = 0; i < k && position == -1; i++)
    {
        if (numbers[i] == target)
        {
            position = i;
        }
    }
    return position;
}

int
main(void)
{
    int numbers[1000000];
    int i;
    int search;
    for (i = 0; i < 1000000; i++) {
        numbers[i] = i;
    }

    printf("Enter a number: ");
    scanf("%d", &search);

    printf("%d\n", sizeof(numbers));
    int position = searchMe(numbers, search);

    printf("Position of %d is at %d\n", search, position);
    return 0;
}

推荐答案

int searchMe(int numbers[], int target)

等效于

int searchMe(int *numbers, int target)

对于函数参数,有一条特殊的C规则,它表示将数组类型的参数调整为为指针类型.

There is a special C rules for function parameters that says parameters of array type are adjusted to a pointer type.

这意味着在您的程序中,sizeof numbers实际上产生的是int *指针类型的大小,而不是数组的大小.

It means in your program that sizeof numbers actually yields the size of the int * pointer type and not of the array.

要获取大小,必须在函数中添加第三个参数,并在调用函数时显式传递数组的大小.

To get the size you have to add a third parameter to your function and explicitly pass the size of the array when you call the function.

这篇关于C语言中通过函数的sizeof数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆